Course contentsShow
← JavaScript
Lesson 1348 of 2,72330. Async/AwaitFree lesson

Await in Loops

Using await inside loops processes iterations sequentially, which may be slow for independent async operations.

Await in Loops

You'll learn how using await inside loops processes operations one-by-one, which can be inefficient when operations don't depend on each other.

The Sequential Trap

When you use await inside a loop (like for, while, or for...of), each iteration waits for the previous one to complete before starting. This creates a sequential execution pattern:

async function fetchUserData(userIds) {
  const results = [];
  
  for (const id of userIds) {
    const data = await fetch(`/api/users/${id}`);
    results.push(data);
  }
  
  return results;
}

// With 5 users, if each fetch takes 2 seconds,
// total time = 10 seconds (2 × 5)

Each await pauses the loop until that promise resolves. If you have 10 independent API calls that each take 2 seconds, you'll wait 20 seconds total.

When This Pattern Makes Sense

Sequential awaits in loops are good when operations depend on each other:

async function processOrderSteps(orderId) {
  const order = await fetchOrder(orderId);
  const validated = await validateOrder(order);
  const processed = await chargePayment(validated);
  const shipped = await scheduleShipment(processed);
  return shipped;
}

Here, each step needs the result from the previous one—sequential is correct.

The Performance Problem

When operations are independent, sequential awaits waste time. Instead of waiting in the loop, you'd want to start all operations at once and wait for them together (using patterns you've already learned like Promise.all).

Key Takeaway: Using await in loops makes iterations run one-after-another; this is simple and correct for dependent operations, but can be unnecessarily slow when operations are independent and could run concurrently.