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.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github