Asynchronous sequences
Consume values produced over time, such as results from an async generator.
JavaScript · Type Alias
AsyncIterator is an object whose next() method returns a promise for an iterator result. Built-in async iterators inherit from AsyncIterator.prototype, which makes them usable as async iterables.
AsyncIterator describes objects whose next() method returns a promise for an iterator result. Built-in async iterators inherit from AsyncIterator.prototype, whose Symbol.asyncIterator method returns the iterator itself so it can also be used as an async iterable.
async function* numbers() {
yield 1;
yield 2;
}
for await (const number of numbers()) {
console.log(number);
}An async generator produces an AsyncIterator, which can be consumed directly by a for await...of loop.
Consume values produced over time, such as results from an async generator.
Process stream-like data with for await...of while each value becomes available.
Implement a custom object that exposes asynchronous next() operations.
An AsyncIterator is an object whose next() method returns a promise that fulfills with an iterator result. Its prototype also supplies Symbol.asyncIterator(), allowing the object to be consumed as an async iterable.
Follow-up: How is it normally consumed? Use for await...of, which obtains the async iterator through Symbol.asyncIterator() and awaits each result from next().
AsyncIterator.prototype[Symbol.asyncIterator]() returns the current iterator object. This makes an async iterator also satisfy the async iterable protocol without creating a separate wrapper.
Follow-up: Why does this matter in practice? Syntax such as for await...of can call the method automatically and iterate the same object.
Async generator functions return AsyncIterator objects. Those objects can be passed directly to for await...of, which repeatedly awaits next() until the returned result has done set to true.
Follow-up: Can for await...of consume synchronous iterables too? Yes; if no async iterator exists, it falls back to a synchronous iterator and wraps its results asynchronously.
AsyncGeneratorAsyncIterator.prototypeAsyncIterator.prototype[Symbol.asyncIterator]()Symbol.asyncIteratorfor await...of