Using async/await with a forEach loop?

Better Stack Team
Updated on March 11, 2024

In Node.js, the forEach loop is not compatible with the async/await syntax as it does not wait for promises. But fear not, as there are two alternatives:

The for(… of …) loop

If you would like to handle asynchronous operations in order one by one (that means sequentially) you can use the following syntax utilizing the for(const item in list) syntax:

 
async function processInLoopAsync(list){
    for (const item in list){
        const result = await operationAsync(item);
        console.log(result);
    }
}

In this example, the asynchronous operation is represented by an async function operationAsync. This asynchronous operation is being processed in a loop and each time we wait until the asynchronous operation is finished before we move to the next one. This will result in slower execution in comparison with parallel execution shown below, but it finds its use in cases where the next (async) operation might depend on the result of the previous one.

The Promise.all with map

In this example, we will handle the asynchronous operation not one by one (sequentially) but we will process parallel - them all at once (sort of).

 
async function processParallelAsync(list) {
  await Promise.all(list.map(async (item) => {
    const result = await operationAsync(item);
    console.log(result);
  }));
}

In this example, the execution will not be stopped to wait for each promise to resolve, but rather wait for all of them to resolve at once. This is useful when we need to do multiple asynchronous operations that are independent of each other.

Choose whatever works best for you. If you have multiple independent async jobs that can be run parallel - choose Promise.all. If you have multiple jobs where each one needs the previous one to finish - choose for loop.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.