Process asynchronous streams
Data arrives over time, such as network responses or delayed events.
JS Puzzles · Const
Async generators produce sequences lazily while allowing asynchronous work between values. Declare them with async function* and consume them using for await...of.
An async generator combines generator-style lazy production with asynchronous operations. Declare it with async function*, use yield to produce values, and consume the returned async iterable with for await...of; calls to next() produce promises.
async function* name() { yield value; }The generator function returns an asynchronous iterable whose next() method returns promises.
async function* to create an async generator function.async modifier changes the generator so its iteration proceeds asynchronously.for await...of loop.next() as returning an iterator result immediately is incorrect; it returns a promise.for await...of, not ordinary for...of, when consuming an async iterable.async function* numbers() {
await new Promise(resolve => setTimeout(resolve, 10));
yield 1;
yield 2;
}
for await (const number of numbers()) {
console.log(number);
}The loop asynchronously consumes each value produced by the generator.
Data arrives over time, such as network responses or delayed events.
A producer should avoid creating all results before the consumer requests them.
A sequence requires await between yielded values.
Declare an async generator with async function*. It can use both await for asynchronous work and yield for lazy value production, and calling it returns an async iterable object.
Follow-up: How should its output be consumed? Use for await...of, which waits for each asynchronously produced value.
next() return on an async generator?Each call to next() is asynchronous and returns a promise. The promise eventually provides the iterator result for the next yielded value.
Follow-up: Why is this useful for streaming? It lets production and consumption proceed on demand as asynchronous data becomes available.
Async generators are useful when a sequence arrives asynchronously, such as data downloaded in chunks. They allow asynchronous operations inside the generator while preserving generator-style iteration.
Follow-up: What syntax replaces synchronous iteration? Use for await...of rather than for...of.
async iteratorsfor await...ofSymbol.asyncIteratoryieldawait