Awaiting in Loops Without Intent
You'll learn: How to spot unintended sequential execution when using await inside array methods like forEach and map.
The Problem with forEach and map
When you use await inside a forEach or map callback, it doesn't work the way you might expect. These array methods don't wait for async operations—they fire off all callbacks immediately and then move on. This can lead to two problems:
- Ignored Promises:
forEachdoesn't collect return values, so your awaited Promises just float away unhandled - False sense of control: You think you're awaiting, but your code continues past the loop immediately
Why This Happens
Think of forEach like a messenger who drops off letters at every house but doesn't wait for replies. Even if each house takes time to respond (async operation), the messenger finishes their route instantly.
// ❌ This doesn't wait for any fetch to complete
async function badExample() {
const ids = [1, 2, 3];
ids.forEach(async (id) => {
const result = await fetch(`/api/${id}`);
console.log(result);
});
console.log('Done!'); // Prints BEFORE any fetch completes
}
The await inside forEach only pauses that specific callback, not the overall loop or your function.
The Right Approach
Use a traditional for...of loop when you need sequential execution, or use map with Promise.all for parallel execution:
// ✅ Sequential with for...of
for (const id of ids) {
const result = await fetch(`/api/${id}`);
console.log(result);
}
// ✅ Parallel with map + Promise.all
await Promise.all(ids.map(async (id) => {
return fetch(`/api/${id}`);
}));
Key Takeaway: Never use await inside forEach or standalone map—the loop won't wait. Use for...of for sequential operations or combine map with Promise.all for parallel execution.