JavaScript Reference ยท Iterators, Generators and Symbols
Async generators and async iteration
Reference for JavaScript async generators and async iterables: async function*, Symbol.asyncIterator, for await...of, early exit and streaming-style examples.
An async generator combines generators with promises. You declare it with async function*; it can use both await and yield, and calling it returns an async generator object. Each next() call returns a promise of the usual { value, done } result, so values can arrive over time: pages from a server, lines from a stream, ticks from a timer.
Objects that provide a [Symbol.asyncIterator]() method are async iterables. You consume them with for await...of, which waits for each result before running the loop body.
async function* pages() { for (let page = 1; page <= 3; page++) { yield await loadPage(page); } } for await (const items of pages()) { render(items); }
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
How it works
async function*returns an object withnext(),return()andthrow(), each returning a promise, and a[Symbol.asyncIterator]()that returns the object itself.awaitinside the generator pauses it;yield valuealso awaitsvaluefirst if it is a promise, so consumers receive plain values, never promises.- Calls to
next()are queued: if you call it twice without waiting, the generator still handles them one at a time, in order. - If the body throws, the promise returned by the current
next()rejects, and the generator is finished. In afor awaitloop that becomes an exception you can catch withtry...catch. breakorreturninsidefor await...ofcalls the iterator'sreturn()method, which triggersfinallyblocks (the second example prints "feed closed").
for await...of with other values
for await...of also accepts ordinary iterables. It awaits each item, which gives a tidy way to process an array of promises in order:
for await (const response of [fetch("/a"), fetch("/b")]) { console.log(response.status); }
All the requests start at once, because the array is built first; only the handling is sequential.
Usage notes
- Where it is allowed.
for awaitneeds an async function or a module (top-level). Async generators themselves can be methods too:async *name() {}. - Sequential by design. The next item is requested only after the loop body finishes with the previous one, which gives natural back-pressure.
- Bridging callbacks. Event sources need a small queue to become async iterables. Many platform APIs (such as readable streams in newer environments) are already async iterable.
- Collect results with
Array.fromAsync(), a newer static method; check a compatibility table before relying on it. - Do not forget cleanup. Put resource release in
finallyso early exit closes connections or files. - Errors and cancellation. Pair long-running iteration with an
AbortSignaland check it between items. - Not the same as an iterable of promises: an async generator yields values later; an array of promises already exists.
Browser support
Async generators and for await...of are supported in all current browsers and Node.js. Array.fromAsync() is more recent.