Home > Software design >  How to return data in foreach loop having multiple async functions inside
How to return data in foreach loop having multiple async functions inside

Time:04-28

I am calling this function using await and store the data in the result variable. But the function returns without completing the foreach loop. How can I make this function return only if the foreach loop ends?

let result = await prepareStocks(data);

async function prepareStocks(incomingStocks) { 
    var stockCodes = incomingStocks.stocks.split(',');
    var stockPrices = incomingStocks.trigger_prices.split(',');
    var alertName = incomingStocks.alert_name;
    stockCodes.forEach(async(stocks, index) => {

        if (stockPrices[index] > 100) {

            var stockCodes = {
                code: stocks,
                price: stockPrices[index],
                orderType: (urls.buy.includes(alertName) ? 'BUY' : 'WATCH'),
                target: await setSellPrice(stockPrices[index], 1),
                stopLoss: await setStopLoss(stockPrices[index], 1),
            }
            STOCKS.push(stockCodes);
        }

    });
    return STOCKS;

}

CodePudding user response:

Try using Promise.all

Something like this =>

let result = await prepareStocks(data);
async function prepareStocks(incomingStocks) { 
    var stockCodes = incomingStocks.stocks.split(',');
    var stockPrices = incomingStocks.trigger_prices.split(',');
    var alertName = incomingStocks.alert_name;


    const STOCKS = await Promise.all(stockCodes.map(async (stocks, index) => {
        if (stockPrices[index] > 100) {

            var stockCodes = {
                code: stocks,
                price: stockPrices[index],
                orderType: (urls.buy.includes(alertName) ? 'BUY' : 'WATCH'),
                target: await setSellPrice(stockPrices[index], 1),
                stopLoss: await setStopLoss(stockPrices[index], 1),
            }
            return stockCodes;
        }
    })

    return STOCKS;
}

CodePudding user response:

After reading the async/await part, I was wondering there is nothing wrong with the way how async/await is used & STOCKS must be returned with expected values. So, I setup a simulation as follows & ran the code.

async function setSellPrice(price) { return new Promise(function resolver(resolve) {setTimeout(function someTimeLater() { resolve(price)});}); }
async function setStopLoss(price) { return new Promise(function resolver(resolve) {setTimeout(function someTimeLater() { resolve(price)});}); }
const data = { stocks: 'A,B,C'. trigger_prices: '100,120,140', alert_name: 'XYZ' };
let result = await prepareStocks(data);

And got STOCKS not defined error.

Your code was correct in terms of how async/await works. The problem with the original code was, the STOCKS variable was not defined. I am assuming, it was not defined anywhere else. So, doing the following works as expected.

let result = await prepareStocks(data);

async function prepareStocks(incomingStocks) { 
    const STOCKS = [];
    var stockCodes = incomingStocks.stocks.split(',');
    var stockPrices = incomingStocks.trigger_prices.split(',');
    var alertName = incomingStocks.alert_name;
    stockCodes.forEach(async(stocks, index) => {

        if (stockPrices[index] > 100) {

            var stockCodes = {
                code: stocks,
                price: stockPrices[index],
                orderType: (urls.buy.includes(alertName) ? 'BUY' : 'WATCH'),
                target: await setSellPrice(stockPrices[index], 1),
                stopLoss: await setStopLoss(stockPrices[index], 1),
            }
            STOCKS.push(stockCodes);
        }

    });
    return STOCKS;

}
  • Related