The Anti-Pattern: Awaiting in Loops
You'll learn: How to spot and fix the common mistake of using await inside loops, which accidentally creates slow, sequential execution.
The Trap
When you write await inside a for or while loop, you're unknowingly forcing each async operation to wait for the previous one to complete — even when those operations could run independently. This is like standing in line at a coffee shop where each person must wait for the previous order to be completely finished before placing theirs, even though multiple baristas could work simultaneously.
The Problem in Code
// ❌ Anti-pattern: Sequential execution
async function fetchUserData(userIds) {
const results = [];
for (const id of userIds) {
const data = await fetch(`/api/user/${id}`);
results.push(data);
}
return results;
}
If you have 10 user IDs and each request takes 1 second, this takes 10 seconds total because each await blocks the loop.
The Solution
Start all promises before awaiting them:
// ✅ Parallel execution
async function fetchUserData(userIds) {
const promises = [];
for (const id of userIds) {
promises.push(fetch(`/api/user/${id}`));
}
return await Promise.all(promises);
}
Or more concisely with .map():
async function fetchUserData(userIds) {
const promises = userIds.map(id => fetch(`/api/user/${id}`));
return await Promise.all(promises);
}
Now all 10 requests fire simultaneously, completing in ~1 second instead of 10.
Key Takeaway: Avoid await directly inside loops unless you truly need sequential execution. Collect promises in an array first, then await them with Promise.all() for concurrent execution.