JavaScript · Middle · Question 21 of 75
Why doesn't forEach wait for async callbacks?
items.forEach(async (item) => { await save(item); });
console.log("done");- ✓Correct answer:
forEachignores the returned promises - "done" is printed immediately - 2
forEachwaits for all promises and then prints "done" - 3The code crashes:
forEachdoesn't accept async functions
Explanation
The callback returns a promise, but forEach doesn't use it. You need for...of with await (sequential) or await Promise.all(items.map(save)) (parallel).