0Pricing
JavaScript Academy · Lesson

Async iterators — for await...of and async generators

Use async generators and for await...of to consume values that arrive over time. Learn Symbol.asyncIterator and simple async pipelines.

Why async iteration?

Goal: Consume values that may come later.

  • for await...of loops over async iterables
  • async function* creates async generators
  • Symbol.asyncIterator marks an object as async-iterable
  • Tiny async map example
Async iterators — for await...of and async generators — illustration 1

async function* and for await...of

An async generator (async function*) yields values that for await...of consumes.

// Use an async generator to yield values (could be delayed in real apps)
(async function () {
  async function* countAsync(n) {
    for (let i = 1; i <= n; i = i + 1) {
      // In real code you could await a delay or I/O here
      yield i;
    }
  }

  for await (const x of countAsync(3)) {
    console.log("async value:", x);
  }
})();
Async iterators — for await...of and async generators — illustration 2

All lessons in this course

  1. Iterable protocol and for...of
  2. Generator functions, yield, and small pipelines
  3. Async iterators — for await...of and async generators
← Back to JavaScript Academy