Sub topic 17
Async Generators for Streams and Pagination
This chapter assumes you know for await...of and Symbol.asyncIterator from the previous chapter, plus generator functions and async/await. An async generator brings those ideas together. It is a function that can await a promise and also yield values, and it produces an async iterator automatically.
Declaring an async generator
You write an async generator as async function*. Inside it, you can use await and yield together. Each call to next() on the result returns a promise for a { value, done } object. That makes the result something for await...of can consume.
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 generator stays paused at each yield until the loop asks for the next value. The await sleep(100) then runs before the next value is produced. The consumer controls the pace, just as it does with a synchronous generator.
Flattening paginated data
Many APIs return data one page at a time. Without a generator, every caller has to track page numbers and know when to stop. An async generator hides that work and gives the caller one flat stream of items.
async function* paginate(fetchPage) {
let page = 1;
while (true) {
const items = await fetchPage(page);
if (items.length === 0) return;
yield* items;
page++;
}
}
// Example usage with a fake data source
const pages = { 1: ['a', 'b'], 2: ['c'] };
const fetchPage = async page => pages[page] ?? [];
(async () => {
for await (const item of paginate(fetchPage)) {
console.log(item); // a, b, c
}
})();Inside an async generator, yield* also accepts a synchronous iterable such as an array, so yield* items passes on each item one at a time. A page is fetched only after the consumer has used up the items from the previous page.
Common errors
| Mistake | What happens | Fix |
|---|---|---|
| Using `for...of` on an async generator | `TypeError`, because the object has no `Symbol.iterator` | Use `for await...of` |
| Forgetting `await` before an API call | You yield promises instead of data | `await` the call inside the generator |
| Calling `fetchPage` again without a stop condition | The loop never ends | Return when a page comes back empty |
Exercise
In the paginate example, the consumer breaks out of the loop right after logging 'a'. How many times is fetchPage called, and why?
Show answer
Once. Page 1 is fetched to produce 'a'. The break calls the generator's return(), so it never resumes to yield 'b' or reach the loop that would request page 2.
Exercise
Write an async generator delayed(values, ms) that yields each element of an array after waiting ms milliseconds.
Show answer
async function* delayed(values, ms) { for (const v of values) { await new Promise(r => setTimeout(r, ms)); yield v; } }