Why does await inside forEach not wait for each iteration?
forEach ignores the promises returned by an async callback, so it starts them all and moves on without waiting. Use for...of with await for sequential work, or Promise.all with map for parallel work.
Explain it simply
forEach is like a manager who hands tasks to everyone and walks away without waiting to see them finished. Each async callback returns a promise, but forEach does not look at it.
The await inside the callback only pauses that one callback, not the loop and not the surrounding function. So code after forEach runs first.
Better options:
for (const x of items) { await ... }for one-by-one order.await Promise.all(items.map(async (x) => ...))for all at once.
Example
async function run() {
[1, 2, 3].forEach(async (n) => {
await null;
console.log("item " + n);
});
console.log("done");
}
run();
// Output: done
// Output: item 1
// Output: item 2
// Output: item 3
async function runInOrder() {
for (const n of [1, 2, 3]) {
await null;
console.log("ordered " + n);
}
console.log("finished");
}What to say in the interview
"forEach does not understand promises: it calls the async callback and ignores the returned promise, so nothing waits. I use for...of with await for sequential steps or Promise.all over map for parallel ones."
Common mistakes
- Putting await in a forEach and then reading results immediately after it.