Why does forEach with async cause problems?
Practice this questionDefinition:
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.
Key points:
-
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.
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.
Interview point:
- The question is both “does the caller wait?” and “how much work starts at once?”