A normal generator hands out values one at a time with yield. An async generator can also await between values, so it is perfect for data that arrives slowly: pages from an API, lines from a file or readings from a sensor. You read it with for await...of, which waits for each value before running the loop body. The result is code for streams of data that reads like a simple loop.
In this lesson you will learn
- Writing
async function*generators - Reading them with
for await...of - Hiding API paging behind a generator
- Building reusable async helpers such as
filterandtake - Error handling and stopping early
You should know iterators and generators and promises and async/await.
Async Generators and for await
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
// An async generator can await inside and yield values one at a time
async function* countdown(from) {
for (let n = from; n > 0; n--) {
await wait(100); // pretend each value takes time to arrive
yield n;
}
}
// Fake API: one page of results per request
const pages = [["Dhaka", "Gazipur"], ["Khulna", "Jessore"], ["Sylhet"]];
async function fetchPage(n) {
await wait(50);
return { items: pages[n - 1], hasMore: n < pages.length };
}
// Hide the paging inside a generator; the caller just sees cities
async function* allCities() {
let page = 1, more = true;
while (more) {
const { items, hasMore } = await fetchPage(page);
console.log(` (loaded page ${page})`);
yield* items; // hand over each item of the page
more = hasMore;
page++;
}
}
(async () => {
for await (const n of countdown(3)) console.log("countdown:", n);
console.log("Liftoff!");
for await (const city of allCities()) console.log("city:", city);
})();
Output
countdown: 3
countdown: 2
countdown: 1
Liftoff!
(loaded page 1)
city: Dhaka
city: Gazipur
(loaded page 2)
city: Khulna
city: Jessore
(loaded page 3)
city: Sylhet
async function*declares an async generator: it may use bothawaitandyield.- Calling it does not run the body. It returns an object that produces promises of values, one at a time.
for await (const n of countdown(3))waits for each value, runs the loop body, then asks for the next. It can only be used inside anasyncfunction or a module.allCitieshides the paging. The caller just loops over cities. Each new page is fetched only when the loop has used up the previous one; the “(loaded page …)” lines show when that happens.yield*passes on every item from an array (or another generator) one by one.
Async Pipelines, Early Stops and Errors
const wait = ms => new Promise(r => setTimeout(r, ms));
// Readings from a slow sensor
async function* temperatures() {
const readings = [31, 33, 36, 29, 38, 30];
for (const t of readings) { await wait(30); yield t; }
}
// Reusable async helpers that take one async iterable and give another
async function* filter(source, test) {
for await (const x of source) if (test(x)) yield x;
}
async function* take(source, count) {
if (count <= 0) return;
for await (const x of source) {
yield x;
if (--count === 0) return; // stopping early also stops the source
}
}
(async () => {
const hot = take(filter(temperatures(), t => t >= 33), 2);
for await (const t of hot) console.log("hot reading:", t);
// Collect everything into an array (Array.fromAsync in newer runtimes)
const all = [];
for await (const t of temperatures()) all.push(t);
console.log("all:", all.join(", "));
// for await also works on an array of promises
const jobs = [wait(60).then(() => "report"), wait(20).then(() => "email")];
for await (const done of jobs) console.log("finished:", done);
// Errors thrown inside the generator reach the loop's try/catch
async function* flaky() { yield 1; throw new Error("sensor disconnected"); }
try {
for await (const x of flaky()) console.log("got", x);
} catch (e) {
console.log("caught:", e.message);
}
})();
Output
hot reading: 33
hot reading: 36
all: 31, 33, 36, 29, 38, 30
finished: report
finished: email
got 1
caught: sensor disconnected
filterandtakeeach take an async iterable and give a new one, so they can be chained liketake(filter(source, test), 2).takestops withreturnafter two hot readings. Leaving afor awaitloop early also tells the source generator to stop, so the remaining readings are never produced.- Collecting every value into an array needs a loop. Newer runtimes also offer
Array.fromAsync(source)for this. for awaitworks on a plain array of promises too. It handles them in order: “report” is printed first even though “email” finished sooner. For “whichever is first”, usePromise.raceinstead.- An error thrown inside the generator appears at the loop, where a normal
try...catchhandles it.
| Generator | Async generator | |
|---|---|---|
| Declared with | function* | async function* |
Can use await | No | Yes |
next() returns | { value, done } | A promise of { value, done } |
| Loop with | for...of | for await...of |
| Iterator key | Symbol.iterator | Symbol.asyncIterator |
Common Mistakes
- Using plain
for...ofon an async generator. It throws an error, because the object is not a normal iterable. - Using
for awaitoutside an async function in a classic script, which is a syntax error. - Expecting values in parallel. An async generator is one-at-a-time; use
Promise.allwhen you want many requests at once. - Forgetting that work happens lazily. Nothing is fetched until the loop asks for the next value.
Practice Exercises
Exercise 1. Write an async generator ticks(n, ms) that yields the numbers 1 to n, waiting ms milliseconds before each.
Show answer
async function* ticks(n, ms) {
for (let i = 1; i <= n; i++) {
await new Promise(r => setTimeout(r, ms));
yield i;
}
}
(async () => { for await (const t of ticks(3, 500)) console.log(t); })();
Exercise 2. Write an async helper map(source, fn) that yields fn(x) for each value of an async iterable.
Show answer
async function* map(source, fn) {
for await (const x of source) yield fn(x);
}
// for await (const f of map(temperatures(), c => c * 9 / 5 + 32)) ...
Frequently Asked Questions
Where do async iterables appear in real code?
Node.js file streams and readline interfaces are async iterable, so you can loop over the lines of a file with for await. In browsers, a ReadableStream from fetch can be read the same way in modern engines.
How do I stop an async generator from outside?
Use break or return inside the for await loop, or call the generator’s return() method. Any finally block inside the generator then runs, which is the place to close files or connections.
Summary
async function*combinesawaitandyieldto produce values that arrive over time.for await...ofwaits for each value in turn.- Generators can hide paging and be chained into reusable pipelines.
- Errors reach the loop’s
try...catch, and breaking out stops the source.
