Array.prototype.forEach() is promise-unaware: it invokes your async callback for every item in rapid succession, ignores the returned Promises, and does not pause or await them before moving to the next element or finishing. Instead, use for...of with await for sequential execution, Promise.all() with .map() for concurrent execution, or for await...of when iterating async iterables.
1. Why forEach Fails with async/await
Even when you pass an async function to .forEach(), .forEach() only cares about synchronous execution and never waits for promises to settle.
const delay = (ms, label) =>
new Promise((resolve) => {
setTimeout(() => {
console.log("Done:", label);
resolve(label);
}, ms);
});
async function runWithForEach(items) {
console.log("Start");
// Fires all timers immediately and returns before any finish
items.forEach(async (item) => {
await delay(300, item);
});
console.log("End (runs BEFORE items finish!)");
}
runWithForEach(["A", "B", "C"]);
- No awaiting between iterations: Item
"B"and"C"start almost immediately without waiting for"A". - No awaiting before outer code continues:
"End"logs before the async work completes, and.forEach()itself always returnsundefinedrather than a combinedPromise. - Errors inside
asynccallbacks aren’t caught by outertry/catch: A rejected promise inside anasynccallback becomes an unhandled promise rejection unless caught inside the callback.
2. Better Alternatives: Sequential (for...of) vs. Concurrent (Promise.all)
Pick the pattern that matches how your async operations should run—one after another or in parallel.
// 1. Sequential: awaits each item before starting the next
async function runSequential(items) {
console.log("Sequential start");
for (const item of items) {
await delay(200, item);
}
console.log("Sequential end (after all items finish)");
}
// 2. Concurrent: starts all promises together and awaits all results
async function runConcurrent(items) {
console.log("Concurrent start");
const results = await Promise.all(
items.map((item) => delay(200, item))
);
console.log("Concurrent end:", results);
}
// runSequential(["A", "B", "C"]);
// runConcurrent(["A", "B", "C"]);
- Use
for...of+awaitwhen order matters, operations depend on prior results, or you want to avoid hitting rate limits simultaneously. - Use
Promise.all(items.map(asyncFn))when items are independent and you want maximum throughput—note thatPromise.all()rejects fast if any single promise fails (usePromise.allSettled()if you want every result regardless of failures).
3. Common Traps to Avoid
- Using
.forEach()to build an array of promises: Because.forEach()returnsundefined,Promise.all(items.forEach(...))fails—use.map(...)instead. - Firing thousands of
fetchcalls at once withPromise.all(): Unbounded concurrency can overwhelm APIs or sockets; batch items in chunks when dealing with large lists. - Assuming
for...ofruns in parallel:for...ofwithawaitintentionally runs sequentially, which is safer for ordered writes but slower for independent network calls.
TL;DR: Array.forEach() ignores returned Promises and does not await async callbacks. Use for...of with await for sequential async work or Promise.all(arr.map(...)) for concurrent async work.
Do you need the async operations to run sequentially (one by one), concurrently (Promise.all), or with error tolerance (Promise.allSettled)?
