Using async/await with a forEach loop?
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.
-
Logging in Nodejs
Learn how to start logging with Node.js and go from basics to best practices in no time.
Guides -
Node.js Clustering
Due to Node.js's architecture, deploying a Node.js application on a machine with multiple CPUs typically runs as a single instance on a single CPU, responsible for handling all incoming requests. T...
Guides