gotchaMajor
Async/await in Array.forEach does not work as expected
Viewed 0 times
forEach asyncawait forEachPromise.allfor ofparallelsequential
browsernodejs
Error Messages
Problem
Using async/await inside Array.forEach does not wait for the async operations to complete. The loop finishes immediately while promises are still pending, leading to race conditions or missing data.
Solution
forEach ignores the return value of callbacks, so returned promises are discarded. Use for...of loop instead: for (const item of items) { await processItem(item); }. For parallel execution: await Promise.all(items.map(item => processItem(item))). For controlled concurrency, use p-map or a manual semaphore pattern.
Why
Array.forEach calls the callback but does not await the returned promise. It was designed before async/await existed and has no mechanism to handle promises.
Code Snippets
forEach vs for-of vs Promise.all with async
// WRONG: forEach ignores async
items.forEach(async (item) => { await process(item); });
// RIGHT: sequential
for (const item of items) { await process(item); }
// RIGHT: parallel
await Promise.all(items.map(item => process(item)));Revisions (0)
No revisions yet.