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

Iterating Over Async Iterables

Use for-await-of to consume objects implementing Symbol.asyncIterator, awaiting each yielded promise automatically.

Iterating Over Async Iterables

What you'll learn: How for-await-of automatically awaits each promise from an async iterable, making asynchronous iteration feel synchronous.

The Core Idea

When you have an object that implements Symbol.asyncIterator, you need a way to consume the values it produces. Since each value arrives wrapped in a promise (remember: next() returns Promise<{value, done}>), you'd normally need to manually await each one. That's tedious and error-prone.

for-await-of handles all that awaiting for you automatically. It calls next(), waits for the promise to resolve, extracts the value, and hands it to you—all in a clean loop syntax.

How It Works

// An async iterable we created earlier
const asyncIterable = {
  [Symbol.asyncIterator]() {
    let count = 0;
    return {
      async next() {
        if (count < 3) {
          count++;
          return { value: count * 10, done: false };
        }
        return { done: true };
      }
    };
  }
};

// Using for-await-of to consume it
async function consume() {
  for await (const value of asyncIterable) {
    console.log(value); // 10, 20, 30
  }
}

consume();

Behind the scenes, for-await-of repeatedly calls the iterator's next() method, awaits each returned promise, and gives you the unwrapped value in each loop iteration.

Think of It Like This

Imagine a delivery service that promises packages at irregular intervals. Instead of constantly checking "Has it arrived yet?", for-await-of is like having a smart assistant who waits at the door, receives each package as it arrives, and hands it directly to you.

Key Takeaway: Use for-await-of to cleanly consume async iterables—it automatically awaits each promise from next(), letting you focus on processing values rather than managing asynchronous mechanics.