Streaming remote data
Consume paginated API responses as they arrive without loading all pages first.
TypeScript · Interface
AsyncIterable represents a value that supports asynchronous iteration through Symbol.asyncIterator. Its iterator produces promise-based iteration results for use with for await...of.
AsyncIterable describes an object that can provide an asynchronous iterator through Symbol.asyncIterator. Its iterator advances asynchronously, so iteration results are delivered through promises and can be consumed with for await...of.
interface AsyncIterator<T> {
next(value?: any): Promise<IteratorResult<T>>;
return?(value?: any): Promise<IteratorResult<T>>;
throw?(e?: any): Promise<IteratorResult<T>>;
}async function* values(): AsyncGenerator<number> {
yield 1;
yield 2;
}
async function total(source: AsyncIterable<number>): Promise<number> {
let result = 0;
for await (const value of source) result += value;
return result;
}
total(values()).then(console.log);An async generator produces values through the async-iteration protocol, and the function consumes any compatible asynchronous iterable with for await...of.
Consume paginated API responses as they arrive without loading all pages first.
Represent asynchronous file, network, or database records as a uniform iteration source.
Yield intermediate results from asynchronous computation.
AsyncIterable is the asynchronous counterpart of Iterable: it exposes Symbol.asyncIterator, whose result is an AsyncIterator. The iterator's next, return, and throw operations produce promises for iteration results.
Follow-up: What enables consumption syntax? A compatible object can be consumed with for await...of, provided the runtime supplies Symbol.asyncIterator and Promise support.
Each asynchronous iterator operation returns a Promise<IteratorResult<T>> rather than an IteratorResult<T> directly. This lets callers await progress before receiving the next iteration result.
Follow-up: What does the protocol require at runtime? A Symbol.asyncIterator method must return an AsyncIterator, and Promise support must be available.
Async generators are async functions that can yield partial computation results. They can also delegate with yield* to either an ordinary iterable or an async iterable.
Follow-up: What compiler settings matter for older targets? Include esnext in lib for the declaration, and use --downlevelIterators for ES5 or ES3 targets.
AsyncIteratorAsyncGeneratorSymbol.asyncIteratorfor await...ofIterableIteratorResult