Sub topic 11
Async Generators and for await...of
So far, every awaited operation in this tutorial produced a single value: one response, one user record, one timer result. Some data does not arrive all at once. It comes over time, in pieces: pages from a paginated API, lines from a large file, messages from a socket, chunks from a network stream. This chapter covers the language tools built for that case. An async generator produces values over time, and the for await...of loop consumes them one at a time.
This chapter assumes you are comfortable with async functions, await, and try/catch in async code from earlier chapters. It also helps to know ordinary (synchronous) generators, meaning function* and yield, and the regular for...of loop. If generators are new to you, a sync generator is a function that can pause at each yield and hand a value to whoever is iterating it.
The Problem: Many Values, Each One Delayed
A Promise represents one future value. An array holds many values that already exist. Neither fits a sequence where each item has to be waited for. You could return a Promise of an array, but then the caller waits for everything before it sees anything, and you hold the whole data set in memory. You could take a callback per item, but then you lose break, return, and try/catch across the loop.
Async iteration gives you a sequence of Promises that you can loop over with ordinary control flow.
| Tool | Values | Each value available | Consumed with |
|---|---|---|---|
| Array | Many | Immediately | `for...of` |
| Sync generator | Many, lazily | Immediately when asked | `for...of` |
| Promise | One | Later | `await` |
| Async generator / async iterable | Many, lazily | Later | `for await...of` |
The Async Iteration Protocol
for await...of works with any object that follows the async iteration protocol. Async generators are the convenient way to build such objects, but the protocol itself is small:
- The object has a method under the key
Symbol.asyncIteratorthat returns an iterator. - The iterator has a
next()method that returns a Promise. - That Promise fulfills with a result object
{ value, done }. Whendoneistrue, the loop stops. - Optionally, the iterator has a
return()method. The loop calls it when it exits early, so the source can clean up.
Here is a hand-written async iterable that yields three numbers, 50 ms apart:
const ticker = {
[Symbol.asyncIterator]() {
let i = 0;
return {
next() {
i++;
return new Promise(resolve => {
setTimeout(() => {
if (i <= 3) {
resolve({ value: i, done: false });
} else {
resolve({ value: undefined, done: true });
}
}, 50);
});
},
return() {
console.log('ticker cleanup');
return Promise.resolve({ value: undefined, done: true });
}
};
}
};
async function main() {
for await (const n of ticker) {
console.log('tick', n);
}
console.log('loop finished');
}
main();
// tick 1, tick 2, tick 3, loop finishedThe return() method does not run here because the loop ended normally, with done: true. It only runs when the consumer leaves early, which is covered below.
Writing iterators by hand works, but the state tracking gets messy quickly. An async generator writes the same thing as straight-line code.
Async Generators
An async generator is declared with async function*. Inside it you can use both await and yield. Calling it does not run the body. It returns an async generator object that already implements the protocol above.
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
async function* ticker(limit) {
try {
for (let i = 1; i <= limit; i++) {
await delay(50);
yield i;
}
} finally {
console.log('ticker cleanup');
}
}
async function main() {
const gen = ticker(2);
console.log(await gen.next()); // { value: 1, done: false }
console.log(await gen.next()); // { value: 2, done: false }
console.log(await gen.next()); // ticker cleanup, then { value: undefined, done: true }
}
main();Calling next() by hand shows what the loop does for you. Each next() call resumes the body until the next yield. The returned Promise fulfills with that yielded value. When the body finishes, the Promise fulfills with done: true.
A few rules are worth knowing:
yield somePromiseawaits the Promise first, so the consumer receives the fulfilled value and never a Promise. If the Promise rejects, the rejection is thrown inside the generator at thatyield.- A
return valuestatement ends the sequence.for await...ofignores the returned value, just asfor...ofdoes. - If you call
next()several times without waiting, the calls are queued. The generator still runs one step at a time, and the Promises fulfill in order.
The sequence below shows how one loop iteration passes control back and forth between the consumer and the generator.
A Realistic Use: Paginated APIs
Pagination is the most common real use. The API returns a page of items and a cursor for the next page. The generator hides the cursor handling, so the caller sees one flat stream of items. This example simulates the API so it runs anywhere:
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
const DATA = Array.from({ length: 7 }, (_, i) => ({ id: i + 1 }));
// Simulated API: returns up to 3 items per page plus a cursor
async function fetchPage(cursor) {
await delay(50);
console.log(`fetched page at cursor ${cursor}`);
const items = DATA.slice(cursor, cursor + 3);
const next = cursor + 3 < DATA.length ? cursor + 3 : null;
return { items, next };
}
async function* allItems() {
let cursor = 0;
try {
while (cursor !== null) {
const page = await fetchPage(cursor);
yield* page.items; // yield each item of the page in turn
cursor = page.next;
}
} finally {
console.log('allItems closed');
}
}
async function main() {
for await (const item of allItems()) {
console.log('item', item.id);
}
}
main();
// fetched page at cursor 0, item 1..3,
// fetched page at cursor 3, item 4..6,
// fetched page at cursor 6, item 7, allItems closedyield* hands off to another iterable. Inside an async generator it accepts both async and sync iterables, so yield* page.items yields each array element one by one.
The generator is lazy. It fetches the next page only after the consumer has asked for every item on the current page. Nothing is fetched before the loop starts.
Leaving Early: break, return, and Cleanup
Laziness matters most when the consumer stops early. When a for await...of loop exits through break, return, or a thrown error, it calls the iterator's return() method. For an async generator, that resumes the body as if a return statement sat at the paused yield. Any finally blocks run, and no more code runs after them.
async function findFirst(predicate) {
for await (const item of allItems()) {
if (predicate(item)) {
return item; // triggers allItems().return(), so its finally runs
}
}
return undefined;
}
findFirst(item => item.id === 2).then(found => console.log('found', found));
// fetched page at cursor 0
// allItems closed
// found { id: 2 }Only one page is fetched. This is the main reason to use a generator instead of collecting everything into an array: the caller decides how much work happens. Put resource cleanup, such as closing a file handle, releasing a lock, or cancelling a request, in a finally block inside the generator so it runs however the loop ends.
Errors in Async Iteration
Errors move in both directions with ordinary try/catch:
- If the generator throws, or an
awaitinside it rejects, the Promise fromnext()rejects.for await...ofthrows that error at the loop, where a surroundingtry/catchcan handle it. - After throwing, the generator is finished. Later
next()calls fulfill withdone: true, so you cannot "skip" a bad item and keep going with the same generator.
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
async function* flakySource() {
yield 1;
await delay(50);
throw new Error('connection lost');
}
async function main() {
try {
for await (const n of flakySource()) {
console.log('got', n);
}
} catch (err) {
console.log('stream failed:', err.message);
}
}
main();
// got 1
// stream failed: connection lostIf you want to keep going after per-item failures, catch inside the generator and yield a result object, for example { ok: false, error }, instead of throwing.
Built-in Async Iterables
You will often consume async iterables that you did not write. In Node.js, readable streams and readline interfaces are async iterable. Here, for await reads a file line by line without loading it all into memory:
const fs = require('node:fs');
const readline = require('node:readline');
fs.writeFileSync('sample.log', 'INFO start\nERROR disk full\nINFO done\n');
async function countErrors(path) {
const rl = readline.createInterface({
input: fs.createReadStream(path),
crlfDelay: Infinity
});
let errors = 0;
for await (const line of rl) {
if (line.startsWith('ERROR')) errors++;
}
return errors;
}
countErrors('sample.log').then(n => console.log('errors:', n)); // errors: 1Web ReadableStream objects, such as response.body from fetch, are async iterable in Node.js 18 and later and in current Firefox and Chrome. Safari support has arrived more recently, so check your target browsers or fall back to getReader().
for await Over Sync Iterables, and a Trap
for await...of also accepts plain sync iterables. It awaits each element, so looping over an array of Promises appears to work:
const delay = (ms, v) => new Promise(resolve => setTimeout(() => resolve(v), ms));
async function main() {
const promises = [delay(100, 'a'), delay(50, 'b')];
for await (const v of promises) {
console.log(v); // a, then b (in array order, not finish order)
}
}
main();The trap is rejection. The loop only attaches a handler to each Promise when it reaches that Promise. Suppose the second Promise rejects while the loop is still waiting on the first. Nothing is handling the second Promise yet, so the runtime reports an unhandled rejection, and Node.js crashes the process by default. Your try/catch around the loop never gets the chance.
Sequential by Design
for await...of is sequential. It does not request item N+1 until the loop body for item N has finished, including any awaits in the body. That gives you natural backpressure: a slow consumer automatically slows the producer, and memory use stays flat. The cost is throughput. If each item needs an independent 200 ms request, processing 100 items takes about 20 seconds. When order and backpressure don't matter, collect a batch and process it with Promise.all, applying the sequential-versus-parallel trade-off from the earlier chapter one batch at a time.
Exercise
Write an async generator take(iterable, n) that yields at most the first n values from any async iterable and then stops. Make sure the source's cleanup runs when you stop early. Test it with the allItems() generator from this chapter and n = 4.
Show answer
Wrapping the source in for await...of and returning once n values are yielded makes the inner loop call the source's return(), so its finally runs: async function* take(iterable, n) { if (n <= 0) return; let count = 0; for await (const value of iterable) { yield value; count++; if (count >= n) return; } } async function main() { for await (const item of take(allItems(), 4)) { console.log(item.id); } } main(); It prints the fetches for cursors 0 and 3, then items 1 to 4, then "allItems closed". The third page is never fetched.
Exercise
A generator does const page = await fetchPage(cursor); yield* page.items;. A consumer runs for await (const item of gen) { await saveToDatabase(item); }, and each save takes 100 ms. Pages hold 3 items, and fetchPage takes 50 ms. Roughly how long does processing 9 items take, and why isn't the next page fetched while the saves run?
Show answer
About 1050 ms: three page fetches (3 × 50 ms) plus nine saves (9 × 100 ms). The generator stays paused at a yield until the consumer calls next(), and for await...of only calls next() after the loop body, including its await, finishes. So fetching and saving never overlap.
Exercise
Why can for await (const r of [p1, p2]) crash a Node.js process even though the loop is inside try/catch, and what should you use instead?
Show answer
The loop attaches a handler to p2 only after p1 settles. If p2 rejects first, it is an unhandled rejection at that moment, and Node.js terminates by default before the loop ever reaches p2. Use Promise.all (or Promise.allSettled) so handlers are attached to every Promise immediately.