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

What is the best way to interpret the JavaScript code within a Vue/Quasar project?

Sample Code: <script type="text/javascript" src="https://widget.example.com/widgets/<example_id>.js" async defer></script> I am looking to integrate this code into Quasar Framework and utilize it with Vue.js. Do you have any suggesti ...

A collection of jQuery objects that consist of various DOM elements as their properties

Seeking a more concise and potentially more streamlined approach using jQuery. I have an object called lbl which represents a div. Inside this div, there is a span tag that contains the properties firstName and lastName of the lbl object. Here's how t ...

Angular factory transforming service

I am looking to transform the 'i18n' function into a factory in order to return a value instead of just setting it. Any suggestions or tips would be greatly appreciated! services.factory('i18nFactory', function() { var language = ...

Modifying the font style within an ePub document can affect the page count displayed in a UIWebView

Currently in the development phase of my epubReader app. Utilizing CSS to customize the font style within UIWebView, however encountering a challenge with the fixed font size causing fluctuations in the number of pages when changing the font style. Seeki ...

Tips for generating and invoking a promise within NodeJS

I have been attempting to access Firestore using a function I created that includes a collection variable. var fetchDataFromFirestore = function(collection, doc){ return promise = new Promise(function(resolve,reject){ //If doc param is null Quer ...

Creating a Javascript Polling feature in a Ruby on Rails application

I'm completely new to using javascript and I am currently working on implementing polling in a rails application to display a simplified feed of activities from an activity model. I am closely following the Railscast tutorial on polling which can be f ...

What is the best way to retrieve the name of a Meteor package from within the

As I work on developing a package, I am looking for ways to dynamically utilize the package's name within the code. This is particularly important for logging purposes in my /log.js file. My main query is regarding how I can access the variable that ...

Occasionally, the Twilio SMS and Whatsapp functionality fails to trigger within a serverless function when utilizing the Next.js API route on Vercel's production

In the following code snippet, you can see the implementation of the NextJS API route that is currently functional in a local environment. export default async function handler(request, response) { const accountSid = process.env.TWILIO_ACCOUNT_SID; con ...

Cannot transfer variables from asynchronous Node.js files to other Node.js files

Is there a way to export variable output to another Node.js file, even though the asynchronous nature of fs read function is causing issues? I seem to be stuck as I am only getting 'undefined' as the output. Can someone help me identify where I ...

Experiencing difficulties with a cross-domain jQuery/AJAX service request

After extensively researching various threads both on this platform and elsewhere, I have been trying to successfully execute a cross-domain AJAX call. The scenario involves a Restful WCF service that simply returns a boolean value. The service is configur ...

Neglecting specific packages in package-lock.json

Currently facing a perplexing dilemma with no clear solution in sight. In our ongoing project, we rely on npm for package management. Although we haven't been utilizing package-lock.json file lately, the need to reintroduce it has emerged. The issue ...

What could be causing this function to malfunction?

Apologies for any inaccuracies in technical terms used here. Despite being proficient in English, I learned programming in my native language. I am currently working on a project using the latest version of Angular along with Bootstrap. I'm unsure if ...

Is there a way to store a JSON object retrieved from a promise object into a global variable?

var mongoose = require('mongoose'); var Schema = mongoose.Schema; const NewsAPI = require('newsapi'); const { response } = require('express'); const newsapi = new NewsAPI('87ca7d4d4f92458a8d8e1a5dcee3f590'); var cu ...

Error encountered when passing props to child components in NextJS

I have a file that defines two types: type IServiceItems = { fields: { name: string; description: string; logo: { fields: { file: { url: string; }; }; }; }; }; type ITechItems = { fields: { n ...

Learn the steps to activate on-page editing feature!

Is there a way to make a section of a webpage editable when a button is clicked? (e.g. edit & view on the same page) For instance, imagine you could click "edit" on this very page (the one you are currently reading), and the title and content become edita ...

What is the reason behind FieldSelect returning a string instead of an object like FieldCheckbox?

FieldSelect component from Sharetribe documents is giving me a string, while FieldCheckbox is returning a JSON object. In a specific scenario, I want FieldSelect to store a JSON object. How can I achieve this? Below is the code snippet for reference: I& ...

Having trouble with AngularJS - struggling to diagnose the issue

HTML Page <head> <title>TODO supply a title</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="assets/js/angular.min.js"></script> ...

Differences between applying addClass(undefined) and addClass(null)

At times, it crosses my mind to include a class in a chain, depending on certain conditions. What would be the most fitting semantic value to add no class? For instance: $(".element").performAction().addClass(condition ? "special-class" : undefined).perf ...

Phonegap application functioning smoothly on computer, encountering issues on mobile device

Hey there! I recently developed a phonegap app that retrieves JSON data from a YQL link and presents it to the user. It works perfectly on Google Chrome desktop, but my client mentioned that it doesn't work on his Android 2.3 device. Could you help me ...

Displaying postcode on a category page: A step-by-step guide

I would like to showcase the user input code and present it on the web exactly as entered. <?php #code... ?> Any assistance is greatly appreciated. Please excuse my English. Thank you! ...