Having trouble adding items to an array within a Javascript promise

I am facing an issue with the exported function in a Nextjs app, which acts as an API page. The problem arises when the 'domainnames' array returns nothing in the 200 response.

Interestingly, if I exclude the 'GetDomainStatus()' function and simply push items from 'response.data.results' into 'domainnames', the JSON response is populated properly.

export default function GetSuggestions(req, res){
const keyword = req.query.q;
const tlds = '.com,.net,.io,.org,.co,.xyz,.app,.us,.blog,.shop,.land,.video,.review,.host,.dev';
let queryPath = `${suggestionsURL}?include-registered=false&tlds=${tlds}&include-suggestion-type=true&sensitive-content-filter=true&use-numbers=true&max-length=20&lang=eng&max-results=100&name=${keyword}&use-idns=false`
let domainnames = [];

axios.get(queryPath).then(response => {

  response.data.results.forEach(item => {

      GetDomainStatus(item.name).then(a => {
        domainnames.push({
          name: item.name,
          avail: a
        })
      })
  })
  res.status(200).json(domainnames);
});

}

Does this indicate a scope issue where I might not be able to access the 'domainnames' array from within the promise?

Answer №1

This method seems effective in resolving the issue. While there may be room for improvement, it uses the promise.all approach.

const websiteList = [];
const promiseList = [];

axios.get(queryPath).then(response => {

  response.data.results.forEach(item => {

    let newPromise = CheckDomainAvailability(item.name).then(availability => {
        websiteList.push({
          name: item.name,
          availability: availability
        })
    });
    promiseList.push(newPromise);
  })
  Promise.all(promiseList).then(result => res.status(200).json(websiteList));

});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transformation of firebug console information into a function()

Snippet of JavaScript code: KT_initKeyHandler(b) Firebug console output: KT_initKeyHandler(b=keydown charCode=0, keyCode=90) Corresponding JavaScript function call: KT_initKeyHandler(?) Example: Snippet of JavaScript code: KT_event(b,c) Firebug ...

Remove the post by utilizing the $.ajax function

I am just starting out with using $.ajax and I'm not very familiar with it. I have a button that is meant to delete a user post based on the article ID provided. <button type="button" onclick="submitdata();">Delete</button> When this but ...

The Next.JS application is experiencing an issue where the modal component fails to appear on

I am currently developing an application with Next.JS where users can navigate to a page that displays a table of 'Projects'. Above the table, there is a button that, when clicked, should open a modal for adding a new project. Although I have de ...

I am having trouble with an undefined variable in my expressjs server.js file. How can I properly reference

When setting up ExpressJS, I have a file named server.js where the following code is executed: import { call_method } from '../hereIam.mjs'; const process_db = async () => { console.log(this); // undefined call_method(this); }; console. ...

Display Popover with array mapping in HeadlessUI using Next.js

I am struggling to find a way to close the popover when the next Link is clicked inside. I used the popover from TailwindUI and added the next Link, but despite trying the HeadlessUI closing popover using as={Link}, I have had no luck. ...

Trigger a callback in ASP.NET's CallbackPanel using JavaScript every 10 seconds

I am attempting to automatically trigger the callback of a CallbackPanel using JavaScript in my WebFormUserControl every 10 seconds. While I can trigger it with an ASPxButton and ClientSideEvents, my ultimate aim is to have it start automatically every 10 ...

What is the best way to delete an item (using its specific identifier) from an array within a mongoose/mongoDB model?

In my app, I have a User schema with a favorites key that stores an array of objects, each with a unique id. I am attempting to delete one of these objects based on its id. Here is the code snippet that I believe should accomplish this: User.updateOne({id ...

Customizing listview appearance in asp.net with css and enhancing with javascript

When I print, the css class is not being used although it appears when using the program <script type="text/javascript"> function printDiv() { var divToPrint = document.getElementById('DivIdToPrint'); ...

Incorporating AJAX into ASP Classic through an include file

Can I change the content of the #result div using ASP Classic's Include.File on click with a Bootstrap nav? HTML <body onload=""> <nav class="navbar navbar-light bg-light sticky-top shadow"> span><%= ...

How can I load data into Vuex store before the application starts?

Within the created hook of App.vue, I am initiating a dispatch call to my store. Subsequently, in a child component, I attempt to retrieve this data using a getter. However, an issue arises as the child component is loaded before the data is stored, causin ...

How is it possible that TypeScript does not provide a warning when a function is called with a different number of arguments than what is expected?

I am working on a vanilla JavaScript project in VS Code and have set up jsconfig.json. Here is an example of the code I am using: /** * @param {(arg: string) => void} nestedFunction */ function myFunction(nestedFunction) { // Some logic here } myFu ...

Open a new lead form in Crm 2013 by clicking a button and automatically passing the details of the

I have integrated an Add New Lead button into the main form on the Homepage for contacts. Clicking this button triggers a script that opens a new form and passes "Crm Parameter FirstSelectedItemId" as a parameter. By selecting a contact and clicking crea ...

Is there a way to specifically retrieve the number of likes or followers from Facebook, Twitter, Instagram, and Snapchat in order to display them on my HTML website?

Can you provide guidance on how to obtain the total numbers of likes or followers for our Facebook, Twitter, Instagram, and Snapchat pages without including the plugin boxes or buttons? We are solely interested in the actual numbers. Would this be feasibl ...

How can you ensure that it selects a random number to retrieve items from an array?

I am experiencing an issue with some code I wrote. Instead of displaying a random object from the array as intended, it is showing the random number used to try and display an object. <html> <body> <h1>HTML random objects< ...

Is it possible to have the Target='_blank' attribute open the link in a new window instead of a new tab?

Is there a way to achieve this? When using Firefox, the link opens in a new tab, which I prefer to avoid users having to adjust settings in their browsers. I am looking for a solution where a pop-up contact form appears whenever a user clicks on 'co ...

Unlock the full potential of knockout.js by mastering how to leverage templates recursively

Given the following model and view model for nested categories: function Category(id, name) { var self = this; self.Id = ko.observable(id || '00000000-0000-0000-0000-000000000000'); self.Name = ko.observable(name); self.children ...

Establishing the Initial State of React Context with Data from Apollo Query

In my React.js project, specifically with Next.js, I have implemented a global React context for managing user data. Here is how the context is structured: const UserContext = createContext<{ user: User | undefined; setUser: (u: User | undefined) =& ...

Incorporating a delay into looped HTTP requests while effectively utilizing Promise.all to track their completion

Greetings! In my current project, I am trying to introduce a 50ms delay before each subsequent HTTP request is sent to the server. Additionally, I aim to incorporate a functionality that triggers after all requests have been successfully made. To better e ...

Adding design to distinct element after clicking a button

Struggling with a JS/Jquery issue on my portfolio website, I admit that I am still just an average programmer. My portfolio website has five buttons, each representing a different project. For each project, there is a corresponding text description and an ...

Troubleshooting problems with mapping over data in NextJS using react-query

I recently transitioned to using NextJS (version 13.4.12) and decided to give react-query a try for data fetching. Before adopting react-query, I had been using a custom useFetch hook that was functioning properly. To implement react-query as per recommen ...