liveBook · Manning

Async iteration

As explained in JavaScript in Depth

The JavaScript protocol through which an object asynchronously supplies successive iteration results, typically via a next method returning promises.

An async iterable exposes a [Symbol.asyncIterator]() method that returns an iterator whose next() returns a promise resolving to { value, done }. This language-defined contract lets consumers request values incrementally. section 10.5

const iterable = {
  [Symbol.asyncIterator]() {
    let i = 0;
    return {
      next() {
        if (i >= 5) return Promise.resolve({ value: undefined, done: true });
        return Promise.resolve({ value: i++, done: false });
      }
    };
  }
};

This minimal iterator makes the protocol concrete: each next() call produces a promised iteration result. section 10.5

A for-await-of loop calls next(), awaits its promise, then runs the loop body before requesting another value. That makes iteration consumer-paced: no next() call means no new value is requested. The protocol has no built-in buffer or way to ask a producer to work ahead, so I/O-heavy production can leave the consumer waiting on each round trip. section 10.5 section 10.5.2

A Readable stream bridge

Node.js Readable streams support for-await-of, but their internal buffers remain push-driven; the syntax does not turn the stream into a pure pull source. Web Streams, by contrast, use pull-based reading in this account. section 10.5.3

How JavaScript in Depth covers it

How deep it goes
Defines the iterator contract, loop sequencing, backpressure, and buffering tradeoffs without detailing engine internals.
Examples
Uses a minimal custom iterator and large-file chunk processing; also names file lines, database rows, and paginated API responses.
What you can do after
Apply it via for-await-of to consume async iterables and Readable streams one value or chunk at a time.
How it connects
Bridges async iterables with Node.js Readable streams and Web Streams through for-await-of.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of JavaScript in Depth. The section links point to the parts of the book it draws on.