Sub topic 17
Async Generators for Streams and Pagination
This chapter assumes you know how sync generators pause and resume, how yield* delegates, how try...finally cleans up a generator, and how for await...of consumes an async iterable. You also need to be comfortable with promises and async/await.
An async generator combines two ideas. Like a generator, it pauses at each yield. Like an async function, it can await between yields. The result is a producer of values that arrive over time, such as pages from an API, chunks from a file, or messages from a socket.
The Working Model
You declare an async generator with async function*. Calling it runs none of the body. It returns an async generator object, and that object has three methods: next(), return(), and throw(). Each one returns a promise that resolves to a { value, done } result.
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
async function* ticks(n) {
for (let i = 0; i < n; i++) {
await sleep(100);
yield i;
}
}
(async () => {
for await (const t of ticks(3)) {
console.log(t); // 0, 1, 2, about 100 ms apart
}
})();The object is its own async iterator. Its Symbol.asyncIterator method returns this, which is why for await...of accepts it directly. Inside the body you can use await, yield, yield*, try...catch, and try...finally, and they behave the way they do in the sync versions.
The main differences from a sync generator:
| Aspect | Sync generator | Async generator |
|---|---|---|
| Declaration | `function*` | `async function*` |
| `next()` returns | `{ value, done }` | `Promise<{ value, done }>` |
| `await` in body | Not allowed | Allowed |
| Protocol symbol | `Symbol.iterator` | `Symbol.asyncIterator` |
| Consumed by | `for...of`, spread, destructuring | `for await...of` only |
| `yield promise` | Yields the promise object | Awaits it and yields the result |
| `yield*` target | Sync iterables | Async or sync iterables |
Flattening Paginated APIs
Many APIs return data one page at a time. Without a generator, every caller has to track page numbers, check for the last page, and write nested loops. An async generator keeps that bookkeeping in one place and hands the consumer a single flat stream of items.
const pages = { 1: ['a', 'b'], 2: ['c', 'd'], 3: ['e'] };
const fetchPage = async page => {
console.log(`fetching page ${page}`);
return pages[page] ?? [];
};
async function* paginate(fetchPage) {
let page = 1;
try {
while (true) {
const items = await fetchPage(page);
if (items.length === 0) return;
yield* items;
page++;
}
} finally {
console.log('paginate closed');
}
}
(async () => {
for await (const item of paginate(fetchPage)) {
console.log(item);
if (item === 'c') break;
}
})();
// fetching page 1
// a
// b
// fetching page 2
// c
// paginate closedThis output shows three behaviors:
- Laziness. Page 2 is not requested until the consumer has finished with the items from page 1. Page 3 is never requested.
- Delegation.
yield* itemssends each array element out one at a time. In an async generator,yield*accepts sync iterables as well as async ones. - Cleanup.
breakmakesfor await...ofcallreturn()on the generator. Thefinallyblock then runs, and it mayawait, for example to close a connection. The loop does not move on until that cleanup has finished.
For cursor-based APIs, the generator keeps the cursor in a local variable and loops until the server stops returning a next cursor. The consumer's code stays the same.
Transforming Streams
Async generators also work well as transform stages. Each stage takes an async iterable in and produces another one. The stage below turns arbitrary text chunks into complete lines. That matters because a chunk boundary can fall in the middle of a line.
async function* splitLines(chunks) {
let buffer = '';
for await (const chunk of chunks) {
buffer += chunk;
const parts = buffer.split('\n');
buffer = parts.pop();
yield* parts;
}
if (buffer) yield buffer;
}
async function* fakeChunks() {
yield 'one\ntw';
yield 'o\nthree';
}
(async () => {
for await (const line of splitLines(fakeChunks())) {
console.log(line); // one, two, three
}
})();The source can be any async iterable. In Node.js, readable streams are async iterable, so splitLines(fs.createReadStream('log.txt', { encoding: 'utf8' })) works without changes. Because for await...of also accepts sync iterables, splitLines(['a\nb', 'c']) works too, which makes the stage easy to test.
You can chain stages the same way as the lazy sync pipelines from the earlier chapter: filterAsync(splitLines(source), isError). Each stage pulls from the stage before it only when it is asked for a value. This gives you backpressure: a slow consumer automatically slows the producer, so data never piles up in memory.
Errors
An exception thrown inside an async generator rejects the promise returned by next(). for await...of turns that rejection back into a thrown exception at the loop, so an ordinary try...catch around the loop handles it.
async function* flaky() {
yield 1;
throw new Error('network down');
}
(async () => {
try {
for await (const x of flaky()) {
console.log(x); // 1
}
} catch (err) {
console.log('caught:', err.message); // caught: network down
}
})();Once a generator has thrown, it is finished. Later next() calls resolve to { value: undefined, done: true }. If you want retries, put them inside the generator, around the await fetchPage(page) call, so that one failed request does not end the whole stream.
Common Errors and Gotchas
- Forgetting
awaitin the loop.for (const x of asyncGen())throws a TypeError, because the object has noSymbol.iterator. Usefor await. - Expecting concurrency. An async generator produces values one after another. If you call
next()several times without waiting, the calls are queued and settle in order, but the body still runs one step at a time. To fetch pages in parallel, start several requests yourself, for example withPromise.allover known page numbers. You give up some laziness in exchange for lower latency. - Yielding promises by accident. In an async generator,
yield somePromiseawaits the promise, so the consumer receives the resolved value. If that promise rejects, the generator throws at thatyield. - Leaking resources. If a consumer stops calling
next()without usingbreak,return, or an exception,return()is never called andfinallynever runs. Code that drives the generator by hand withnext()must callreturn()itself when it stops early. - Reuse. An async generator object can be iterated only once, like a sync generator. Call the generator function again to get a fresh stream.
Exercise
In the paginate example, suppose the consumer breaks after receiving item 'a' instead of 'c'. Which lines are logged, and how many times is fetchPage called?
Show answer
The log shows "fetching page 1", "a", then "paginate closed". fetchPage is called once. The break calls return() while the generator is paused inside yield* over page 1's array, so the finally block runs before any later page is requested.
Exercise
Write an async generator take(source, n) that yields at most n items from any async iterable and then stops. Make sure the source is cleaned up when take finishes early.
Show answer
async function* take(source, n) { if (n <= 0) return; for await (const x of source) { yield x; if (--n === 0) return; } }. The return inside for await...of leaves the loop early, which calls source.return(), so the source's finally block runs. Checking n <= 0 first means take(source, 0) never pulls from the source at all.
Exercise
Why does splitLines keep the last element of parts in buffer instead of yielding it right away?
Show answer
The last element is the text after the final newline in what has arrived so far. It may be an incomplete line that the next chunk finishes. The generator yields it only after another chunk confirms a newline after it, or after the source ends, which is handled by the if (buffer) yield buffer line.