Attempting to iterate over an array and utilize a foreach loop to return several sets of data

In my original code, getProductInfo took two parameters (res, sku). However, I now want to pass a set object containing SKU numbers and for each SKU, send the data using res.send.


const activeProductBank = new Set([6401728, 6430161, 6359222, 6368084]);

getProductInfo = (res) => {
    activeProductBank.forEach((SKU) => {
        bby.products(SKU, { show:'sku,name' })
        .then(function(data) {
            res.send(data);
        });
    })
};

I also attempted this approach:

getProductInfo = (res) => {
    const allProductInfo = '';

    activeProductBank.forEach((SKU) => {
        bby.products(SKU, { show:'sku,name'})
        .then(function(data) {
            allProductInfo.concat(data);
        });
    })
    res.send(allProductInfo);
};

I encountered the error message "app listening at http://localhost:3000 (node:25556) UnhandledPromiseRejectionWarning: Error: Exceeded max retries."

Answer №1

To efficiently populate the expected allProductInfo, you can utilize a mix of using ASYNC / AWAIT along with Promise.all.

An important point to note about ASYNC / AWAIT is that it can only be used within an ASYNC function. For more information on this, refer to this link.

The method activeProductBank.map will iterate through all items in your activeProductBank array and generate an array of Promises. These Promises are then passed to Promise.all, which resolves once all the promises in the list have been resolved.

More details about using Promise.all

getProductInfo = async (res) => {

    const allProductInfo = Promise.all(
                                activeProductBank.map(SKU => bby.products(SKU, { show:'sku,name'}))
                            )
    
    res.send(allProductInfo);
};

Alternatively, you can employ a for..of loop to push each productInfo response one by one using the Await call as demonstrated below:

getProductInfo = async (res) => {
    let allProductInfo = [];

    for(let sku of allProductInfo) {
        const productInfo = await bby.products(sku, { show:'sku,name'});
        allProductInfo.push(productInfo);
    }
    
    res.send(allProductInfo);
};

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 locate a function (whether it be a GET, POST, etc.) within index.js using an Express router

I've been trying to set up a router in Express, following a tutorial. However, my code can't seem to find the function get/users. Interestingly, it works fine when I include it in index.js index.js : const express = require('express' ...

What are some javascript libraries that can be used to develop a mobile image gallery for both Android and iPhone

I currently have the touch gallery system in place, but unfortunately it isn't functioning properly on Android devices. ...

Steps to modify the border width upon gaining focus

I am struggling to adjust the border width when my input box is focused. Currently, it has a 1px solid border which changes to a 2px different color solid border upon focus. However, this change in border width is causing the containing div to shift by 1px ...

Formatting Dates in Node.js

Can someone assist me in understanding how to properly format the print date shown below? Thu Sep 06 2018 18:18:26 GMT+0530 I attempted to use console.log(new Date()) However, the output generated was 2018-09-06T12:48:25.776Z I am unsure of how to co ...

Why does Chrome consider this file a document, but Firefox sees it as an image?

I am experiencing an issue with the download GET endpoint in my Express app. Currently, it reads a file from the file system and streams it after setting specific headers. Upon testing the endpoint in Chrome and Firefox, I noticed that the browsers interp ...

When using res.json(), the data is returned as res.data. However, trying to access the _id property within it will result

I'm facing a challenge in comprehending why when I make a res.json call in my application, it successfully sends data (an order object). However, when I attempt to access and assign a specific piece of that data (res.data._id) into a variable, it retu ...

Leveraging the browser's console for transmitting AJAX data

I've created a PHP quiz page that uses AJAX to post answer data when a user clicks on an answer. If the answer is correct, the page then loads the next question using another AJAX function. Here's a snippet of the code: <ul class="choices"> ...

Element dynamically targeted

Here is the jQuery code I currently have: $('.class-name').each(function() { $(this).parent().prepend(this); }); While this code successfully targets .class-name elements on page load, I am looking to extend its functionality to also target ...

There is a lack of 'Access-Control-Allow-Origin' header - Issue encountered while making Food2Fork API request using AJAX

Our team has just embarked on our first project, and I've encountered a roadblock while conducting API testing. Specifically, I am struggling to generate a successful access control header. Is there anyone who can provide assistance in troubleshooting ...

Sorting JSON data using JQuery Ajax

I've encountered an issue with sorting JSON data. Here is the JSON data I'm working with: [ { nom: "TERRES LATINES", numero: "0473343687", image: "http://s604712774.onlinehome.fr/bonapp/api/wp-content/uploads/2016/12 ...

Develop a custom chat feature in HTML with the powerful VueJs framework

Currently, I've been developing a chat plugin for HTML using VueJs. My dilemma lies in creating a versatile plugin that can seamlessly integrate into any website. My ultimate goal is to design a plugin that can be easily deployed on various websites ...

Transform React.js data from MySql into a variable

Hello there! I encountered an issue while working on coding my web app. **I am looking to execute this class only if the "swishes" value retrieved from a table in my MySQL database is greater than 0.** var thepos = 1; export default class W ...

What is the solution to the problem of "Failed to execute 'json' on 'Response': body stream already read"?

enter image description here Encountered Issue: Error in processing JSON data in the Response: body stream already read The error mentioned above is a result of issues within your application's code, not due to Cypress. It occurred due to an unhandle ...

Protractor performs the afterEach function prior to the expectations being met

I am completely baffled by the behavior of this code. Everything seems to be executing correctly up until the 'expect' statement, at which point it abruptly navigates to a new page and runs the afterEach function. I've tried various solution ...

What is the best way to set a default value for a specified Date format retrieved from an API?

Here are examples of different data formats for ReleaseDate: 2014-09-23 09:00:00.923Z /Date(1407369600210)/ If you want to access this information from an API, you can use the following object dot-notation: result.data.Items[0].ReleaseDate Sometimes, ...

Learn how to implement drag-and-drop functionality in React by making a component

I am currently experimenting with dragging a component using the react-dnd library. I wanted to replicate functionality similar to this example, specifically only focusing on dragging at the moment. In my application, I have imported and utilized the rea ...

Using angular2's ngRepeat to iterate over XML data

I have successfully transformed my XML data into JSON format to be utilized in Angular 2 within my view. However, as I attempt to loop through the data using a for(var... loop, I encounter an error message stating that it cannot find name array and that th ...

The function '$.fn.<new_function>' is not a valid function in jQuery

UPDATE: code link with enhanced formatting: UPDATE: code upgraded with enhancements from JSHint http://pastebin.com/hkDQfZy1 I am attempting to utilize $.fn to establish a new function on jQuery objects by this method: $.fn.animateAuto = function(x,y) { ...

Iterating through an object using the forEach method (uncommon practice)

Greetings, I have the following object: data = { name: undefined, age: undefined, gender: undefined }; I am looking to iterate through each key and value pair in this object and perform an action. Here is my attempt: this.data.forEach((item: ...

What is the best way to initiate a local Node.js server specifically when launching a desktop Electron application?

I am looking to ensure that my node js server runs while my electron app is open. One method I have attempted is using the child_process module to execute a shell command as shown below: const {exec} = require('child_process') const startDBServ ...