liveBook · Manning

Async iterable

As explained in JavaScript in Depth

An object that implements JavaScript's asynchronous iteration protocol by providing an async iterator that yields promises for iteration results.

A slow consumer needs a way to keep an incremental producer from running ahead. An async iterable does this by letting the consumer request each value. It is an ECMAScript protocol, not a Node.js or Web Streams API: the object provides [Symbol.asyncIterator](), whose iterator provides next(). Each next() call returns a promise resolving to a result shaped like { value, done }. 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 hand-written iterator exposes the contract directly: next() resolves to a value result until it resolves to a result with done: true. section 10.5

A for-await-of loop calls next(), awaits its result, and runs the loop body before requesting another value. That timing is the backpressure mechanism: if the consumer pauses, it makes no next() call. The producer cannot push another value through the protocol. Unlike Node.js streams or Web Streams, a plain async iterable has no internal chunk queue or way to buffer ahead. If producing a value takes an I/O round trip, the consumer waits for it on each request. section 10.5 section 10.5.2

async function* fetchPages(urls) {
  for (const url of urls) {
    const response = await fetch(url);
    const text = await response.text();
    yield text;  // #A
  }
}
 
for await (const page of fetchPages(urls)) {
  await processPage(page);
}

The generator fetches one page and yields it. It resumes only after the consumer finishes processing that page and requests the next one. section 10.5.1

Async generators avoid implementing the iterator protocol by hand. Each yield suspends execution until the next request, keeping producer and consumer in step. That simplicity has a memory cost of its own: a suspended generator retains its context for as long as the consumer takes to resume it. The model suits file lines, database rows, and paginated responses when consumption naturally sets the pace; it is less suited to throughput-sensitive work that benefits from preparing values ahead. section 10.5.1 section 10.5.2

The syntax does not guarantee that the underlying source is pull-based. A Node.js Readable can be consumed with for-await-of, but its internal buffer remains push-driven. Async iteration over a Web ReadableStream instead sits on a pull-based stream. Across model boundaries, costs and error behavior change too: a rejected next() promise makes the loop throw, so try/catch around the loop can handle the failure. section 10.5.3 section 10.6.1

Pull control is not free. Each iteration incurs promise and result-object work; one Node.js v24 measurement counted eight promises per 4 KB chunk through an async iterable, versus none through a synchronous Node.js stream pipeline. Those counts are runtime- and workload-dependent, not a universal speed ratio. Prefer this model when simple, unavoidable backpressure matters more than buffering ahead, and avoid repeatedly converting between streaming models. section 10.6.3 section 10.8

How JavaScript in Depth covers it

How deep it goes
Defines the iterator contract and traces request timing, generator suspension, buffering limits, errors, and measured per-chunk costs.
Examples
Uses a hand-written iterator, paginated fetching with an async generator, and for-await-of consumption of a Node.js file stream.
What it assumes
Assumes familiarity with JavaScript promises and for-await-of while defining the async iterator contract explicitly.
What you can do after
Build it from scratch with Symbol.asyncIterator or an async generator, and diagnose when for-await-of conceals a buffered stream.
How it connects
Connects for-await-of and async generators to backpressure, promises, Node.js streams, and Web Streams.

Also explained in

Compare how 3 books explain async iterable →

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.