Sub topic 11
Async Generators and for await...of
This chapter assumes you already know how await pauses an async function, and how ordinary generator functions (function*) use yield. Some data does not arrive all at once. Paginated API results, lines from a file, and messages from a socket all show up piece by piece. An async generator lets you produce those pieces over time. A for await...of loop lets you consume them one at a time.
From generators to async generators
A regular generator returns an iterator. Each call to next() gives back { value, done } right away. An async generator is declared with async function*. Its next() returns a Promise of { value, done }. Inside the body you can use both await and yield.
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
async function* countdown(n) {
while (n > 0) {
await delay(100);
yield n--;
}
}
async function run() {
for await (const n of countdown(3)) {
console.log(n); // 3, 2, 1
}
}
run();Each pass through the loop calls next(), awaits the Promise it returns, and binds value to n. The loop ends when done is true. Like await, for await...of only works inside an async function or at the top level of an ES module.
A practical case: paginated data
Async generators are a good fit when the consumer should not have to know how the data is fetched. The generator below hides the paging logic. The caller only sees a stream of items.
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
// Simulated API: returns one page of items and the next page number.
async function fetchPage(page) {
await delay(200);
const pages = { 1: ['a', 'b'], 2: ['c', 'd'], 3: ['e'] };
return { items: pages[page], next: page < 3 ? page + 1 : null };
}
async function* allItems() {
let page = 1;
while (page !== null) {
const { items, next } = await fetchPage(page);
yield* items; // yield each item on this page
page = next;
}
}
async function main() {
for await (const item of allItems()) {
console.log(item); // a, b, c, d, e
}
}
main();The generator is lazy. It fetches page 2 only after the consumer has taken both items from page 1. If the consumer stops early, the remaining pages are never requested.
Stopping early and cleaning up
If you break, return, or throw inside a for await...of loop, JavaScript calls the generator's return() method. That runs any finally block inside the generator, which is where you should release resources such as file handles or connections.
async function* source() {
try {
yield 1;
yield 2;
yield 3;
} finally {
console.log('cleanup');
}
}
async function main() {
for await (const n of source()) {
console.log(n);
if (n === 2) break;
}
}
main(); // 1, 2, cleanupErrors work as you would expect. If the generator throws or awaits a rejected Promise, the error is thrown at the for await line, so a surrounding try/catch handles it.
Common errors
| Mistake | What happens | Fix |
|---|---|---|
| Using `for...of` on an async generator | `TypeError`: the object is not iterable | Use `for await...of` |
| Using `for await` outside an async function (in a script) | `SyntaxError` | Wrap it in an async function or use an ES module |
| `for await` over an array of already-started Promises | Works, but a rejection in a later Promise can go unhandled while you wait on an earlier one | Use `Promise.all` or `Promise.allSettled` for a fixed set of Promises |
| Expecting items to be fetched in parallel | Each `next()` waits for the previous one | Batch requests with `Promise.all` inside the generator |
Exercise
The allItems generator above is consumed by a loop that breaks after logging 'b'. How many times is fetchPage called, and why?
Show answer
Once. The generator is lazy: it only resumes when the loop calls next(). After the loop breaks on 'b', return() is called on the generator, so it never reaches the second fetchPage call.
Exercise
Write an async generator ticks(n, ms) that yields the numbers 1 to n with ms milliseconds between them, and a loop that logs each one.
Show answer
const delay = ms => new Promise(r => setTimeout(r, ms)); async function* ticks(n, ms) { for (let i = 1; i <= n; i++) { await delay(ms); yield i; } } (async () => { for await (const t of ticks(3, 500)) console.log(t); })();