Async & Promiseseasy
Why async/await with forEach is a bug
Explain why `await arr.forEach(async ...)` does not wait, and show correct sequential and parallel alternatives.
Asked at Amazon, Meta, Stripe
Answer
// Pitfall: // forEach ignores returned promises, so outer await does nothing useful. async function wrong(items) { await items.forEach(async (item) => { await save(item) }) console.log('done') // runs before saves finish }
// Sequential (ordered): async function sequential(items) { for (const item of items) { await save(item) } }
// Parallel (faster, unordered completion): async function parallel(items) { await Promise.all(items.map((item) => save(item))) }
// Rule: use for...of for sequential work, Promise.all(map) for parallel work.