Search code examples
node.jsasynchronoussequential

How to run this code in sequential way and get the result in node js


this result is always empty, because it is returned even before the async call is complete

function(myList) {
    let result = []
    
    myList.forEach(async function(element)) {
        //api call
        result.push(status)
    }

    return result
}

Solution

  • You can't use async await with forEach loop. Use map with Promise.all or for of loop that is promise aware. For example:

    const myList = ['abc', 'def'];
    
    for (const foo of myList) {
        const result = await someResultfromApi;
        result.push(element);
    }
    
    return result;