Momu
Momu

Reputation: 33

Trying to pass array and use foreach to send back multiple data

I had getProductInfo orgianlly, as two parameters, where it would be (res, sku). but now I want to pass a set object with sku numbers and for-each res.send the data


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);
        });
    })
};

also tried this

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

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

The error I get "app listening at http://localhost:3000 (node:25556) UnhandledPromiseRejectionWarning: Error: Exceeded max retries"

Upvotes: 0

Views: 42

Answers (1)

Nandu Kalidindi
Nandu Kalidindi

Reputation: 6280

You can use a combination of ASYNC / AWAIT and Promise.all to populate the allProductInfo as expected.

The caveat with ASYNC / AWAIT is that you can only use ASYNC function inside an ASYNC function. More about it here https://javascript.info/async-await

activeProductBank.map will iterate over all your activeProductBank and returns an array of Promises which are then passed over to the Promise.all which then resolves after all the promises in the list are reolved.

Promise.all

getProductInfo = async (res) => {

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

Another approach is to use for..of loop and pushing the response of each productInfo one by one using the Await call like 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);
};

Upvotes: 1

Related Questions