liveBook · Manning

Asynchronous generator

As explained in JavaScript in Depth

A JavaScript generator function that can await asynchronous operations and produces an asynchronous sequence of values.

An asynchronous generator produces values incrementally, suspending at each yield until the consumer requests the next value. That pause creates backpressure without an explicit signal: a slow consumer leaves the producer suspended, so data neither accumulates nor fills a buffer. section 10.5.1

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 fetchPages example combines asynchronous work with yield; for-await-of implicitly calls next() for each iteration, keeping fetching and processing in step. section 10.5.1

Each next() call returns a promise containing { value, done }. Unlike a push-based stream, the generator cannot enqueue values externally: no next() call means no production. This simplicity costs one promise per chunk and retains the entire suspended execution context, including locals, intermediate values, and closures, until resumption or completion. section 10.5.2

Use asynchronous generators with these rules in mind:

  • Treat consumer speed as a memory concern: multiple slow consumers can retain generator contexts and promote their objects into old generation. section 10.5.2
  • Catch failures around the for-await-of loop; an internal throw or rejected next() promise becomes a thrown exception there. section 10.6.1
  • Expect extra care when crossing Node.js stream, Web Stream, and async-iteration boundaries because their error propagation models differ. section 10.6.1

How JavaScript in Depth covers it

How deep it goes
Explains yield suspension, promise allocation, retained execution contexts, implicit backpressure, and error propagation, but not implementation internals beyond those effects.
Examples
Uses a fetchPages generator that awaits fetch and response text before yielding pages for asynchronous processing.
What it assumes
Assumes familiarity with promises, asynchronous iteration, next(), yield, and try/catch error handling.
What you can do after
Apply it via async generators and for-await-of loops, while diagnosing memory retention, backpressure behavior, and propagated failures.
How it connects
Connects async iteration with the iterator protocol, for-await-of, backpressure, promises, garbage collection, Node.js streams, and Web Streams.

Also explained in

Compare how 4 books explain asynchronous generator →

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.