Why does forEach with async cause problems?
Try code in the playgroundUnderstand the concept
forEach calls a callback for each array item but ignores the values returned by those callbacks. An async callback returns a promise, so forEach does not wait for its completion or collect its rejection. Choose a loop or a promise combinator based on whether the operations depend on each other.
Important ideas
-
forEachdoes not wait for promises returned by its callback. -
Use
for...ofwithawaitfor one task at a time. -
Use
Promise.all(items.map(...))for a small batch; limit concurrency for large batches. -
A surrounding
await items.forEach(...)does not fix the issue becauseforEachreturnsundefined. -
Sequential work is appropriate when order matters; concurrent work is appropriate only when operations are independent and resources can handle it.
Work through the example
async function demo() {
const save = async id => `saved ${id}`;
const ids = [1, 2];
for (const id of ids) {
console.log(await save(id)); // One operation at a time.
}
const results = await Promise.all(ids.map(save));
console.log(results); // ['saved 1', 'saved 2']
}
demo();- The second approach starts the small independent batch together; a large real batch needs a concurrency limit.
Can you explain it without the notes?
Why does forEach with async cause problems?
Use your own words. Explain an example and one limitation before checking the explanation.
Check your explanation
forEach calls a callback for each array item but ignores the values returned by those callbacks. An async callback returns a promise, so forEach does not wait for its completion or collect its rejection. Choose a loop or a promise combinator based on whether the operations depend on each other.
Turn this concept into a clear answer.
- The question is both “does the caller wait?” and “how much work starts at once?”
Adapted from 01_JAVASCRIPT_TYPESCRIPT.md · “Why does forEach with async cause problems?”. Examples are study fragments; framework behavior can depend on your version.