Advertisement
Advanced Node.js, Async Patterns

What is a common pitfall when using async/await inside Array.prototype.forEach(), and how do you fix it?

Short answer

forEach() does not wait for or respect returned promises at all -- it ignores the return value of its callback entirely, so if the callback is an async function, forEach() fires them all off essentially in parallel and immediately returns, without ever waiting for any of them to…

Save Node.js mock interview
Advertisement
AModel answer
forEach() does not wait for or respect returned promises at all -- it ignores the return value of its callback entirely, so if the callback is an async function, forEach() fires them all off essentially in parallel and immediately returns, without ever waiting for any of them to complete, which is almost never the intended behavior and can silently swallow rejected promises entirely since there's nothing awaiting them.
// Broken: doesn't wait for any of the async operations
items.forEach(async (item) => { await processItem(item); });
console.log('Done!'); // logs immediately, before any items are actually processed

// Fixed: use a for...of loop for sequential processing
for (const item of items) { await processItem(item); }
console.log('Done!'); // correctly logs only after all items are processed

// Or Promise.all with map() for concurrent processing
await Promise.all(items.map(item => processItem(item)));
Real-world example
A batch job that silently only processed a fraction of its records was traced to using items.forEach(async item => ...) instead of a for...of loop, which caused the function to return and the process to exit before most of the asynchronous database writes had actually completed.
Likely follow-ups
  • Why does map() work correctly with async callbacks when combined with Promise.all(), while forEach() doesn't work in the same pattern?
  • What's the performance tradeoff between the for...of sequential approach and the Promise.all with map concurrent approach?
Related topics