Lazy asynchronous streams
Stream values produced over time without loading the complete sequence first.
JavaScript · Type Alias
AsyncGenerator is the object produced by calling an async generator function. It is both an async iterable and async iterator, and its methods return promises.
An AsyncGenerator is the object produced whenever an async generator function is called. It is both asynchronously iterable and an async iterator: its next(), throw(), and return() operations produce promises, while the generator can pause at yield and resume around awaited work.
async function* name(parameters) { statements }An object returned by an async generator function that conforms to both the async iterable and async iterator protocols; its generator methods return promises.
async function* numbers() {
yield await Promise.resolve(1);
yield 2;
}
for await (const value of numbers()) {
console.log(value);
}Calling an async generator creates an AsyncGenerator. The loop requests values through next(), awaits each promise, and stops when done is true.
Stream values produced over time without loading the complete sequence first.
Combine await-based operations with incremental yield of results.
Consume asynchronous sequences with automatic awaiting and completion handling.
An AsyncGenerator is returned by an async generator function. It implements both the async iterable and async iterator protocols, and its iterator methods return promises.
Follow-up: How is it normally consumed? Use for await...of, which repeatedly requests and awaits iterator results until the result object's done property is true.
Calling next() requests the next sequence result and returns a promise. The fulfilled value is an iterator-result object containing value and done, where done indicates whether execution has finished.
Follow-up: What does passing an argument to next() do? The value is delivered to the suspended yield expression, allowing the generator to receive input when it resumes.
throw() behaves as though a throw statement were inserted at the generator's currently suspended position. The generator may catch the error, continue yielding, or remain rejected if the error is uncaught.
Follow-up: How does return() differ? It injects a return at the suspended position, finishes the generator, and permits cleanup in a finally block.
AsyncGeneratorFunctionAsyncGenerator.prototype.next()AsyncGenerator.prototype.throw()AsyncGenerator.prototype.return()async function*for await...of