liveBook · Manning

Asynchronous generator

As explained in The Joy of JavaScript

An async generator is a generator construct that produces asynchronous iteration, allowing values to be yielded over time with async semantics.

An asynchronous generator produces a sequence of values over time with asynchronous semantics. It combines generator syntax with async iteration, making Promise-based data sources readable piece by piece. section 9.0 section 9.2.3

async function* someAsyncGen() {

}

Declare an asynchronous generator with the async function* signature, then consume its results with for await...of. section 9.2.3

Use asynchronous generators when a computation should expose data incrementally rather than assemble everything first.

  • Read large asynchronous sources such as files, databases, or HTTP responses in chunks, using a moving window instead of loading the entire collection. section 9.0 section 9.2.3
  • Separate stream production from downstream work: one generator can yield parsed objects while consumers count, validate, or transform them. section 9.2.3

Streaming blocks from a file

generateBlocksFromFile reads a file stream, collects complete semicolon-delimited records, parses each JSON block, and yields each object. A consumer can then use for await...of to count blocks or validate them incrementally, skipping the genesis block when necessary. section 9.2.3

How The Joy of JavaScript covers it

How deep it goes
Explains the signature, asynchronous consumption, chunked file processing, parsing, hydration, and validation through worked examples.
Examples
Demonstrates reading blocks.txt, yielding parsed blocks, counting them, and validating hydrated blockchain blocks.
What it assumes
Assumes familiarity with iterators, generators, promises, and async/await while extending those constructs to asynchronous sequences.
What you can do after
Apply it via for await...of to process asynchronous data incrementally and build consumers that count, validate, or transform each value.
How it connects
Connects generators with async iterables, promises, async/await, streams, Fetch API, Node.js streams, and Observables.

Also explained in

Compare how 3 books explain asynchronous generator →

Related concepts

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