Course contentsShow
← JavaScript
Lesson 2035 of 2,72342. Iteration Protocols Deep DiveFree lesson

Breaking and Continuing in For-Await-Of

Use break and continue statements inside for-await-of loops just like regular for loops for control flow.

Breaking and Continuing in For-Await-Of

You'll learn how to control the flow of asynchronous iteration using familiar break and continue statements.

The Same Control Flow Works

Just like in regular for loops, you can use break and continue inside for-await-of loops to control iteration flow. The break statement exits the loop entirely, while continue skips to the next iteration. This works identically in async contexts—you're just controlling when and how you process asynchronous values.

Think of it like walking through a museum exhibit: break means "I'm done, I'm leaving now," while continue means "skip this painting, move to the next one."

Breaking Out Early

When you encounter a condition that means you don't need to process any more items, use break:

async function* generateNumbers() {
  for (let i = 1; i <= 100; i++) {
    await new Promise(resolve => setTimeout(resolve, 100));
    yield i;
  }
}

async function findFirst() {
  for await (const num of generateNumbers()) {
    if (num > 5) {
      break; // Stop iteration entirely
    }
    console.log(num); // Only logs 1, 2, 3, 4, 5
  }
  console.log('Done!');
}

Skipping Items with Continue

Use continue to skip processing certain items but keep iterating:

async function processEvenOnly() {
  for await (const num of generateNumbers()) {
    if (num % 2 !== 0) {
      continue; // Skip odd numbers
    }
    console.log(num); // Only logs even numbers
  }
}

Key Takeaway: break and continue work exactly as expected in for-await-of loops, giving you precise control over asynchronous iteration without any special async syntax.