Sub topic 8
Async Iteration with Symbol.asyncIterator
The previous chapter showed how Symbol.iterator lets for...of pull values from an object one at a time. That only works when each value is ready the moment it is asked for. A lot of data arrives late: pages from an API, chunks from a file, messages from a socket. Symbol.asyncIterator is the well-known symbol for that case. It works like Symbol.iterator, except each step returns a promise.
This chapter assumes you know promises and async/await, generator functions (function* and yield), and the synchronous iteration protocol from the previous chapter.
The Async Iteration Protocol
An object is async iterable when it has a method under the key Symbol.asyncIterator. Calling that method returns an async iterator: an object whose next() method returns a promise that resolves to an iterator result, { value, done }.
The sync and async protocols differ in only one place:
| Piece | Sync protocol | Async protocol |
|---|---|---|
| Hook key | `Symbol.iterator` | `Symbol.asyncIterator` |
| `next()` returns | `{ value, done }` | `Promise<{ value, done }>` |
| Optional `return()` | returns `{ value, done }` | returns `Promise<{ value, done }>` |
| Consumer syntax | `for...of`, spread, destructuring | `for await...of` only |
| Generator form | `function*` | `async function*` |
The consumer, for await...of, calls next(), waits for the promise, checks done, and runs the loop body with value. Then it repeats. It does not ask for the next value until the current body has finished, so items are processed strictly one after another.
Writing an Async Iterator by Hand
Writing the protocol by hand once shows exactly what for await expects. This countdown waits 100 ms before producing each number:
const countdown = {
from: 3,
[Symbol.asyncIterator]() {
let current = this.from;
return {
next() {
return new Promise((resolve) => {
setTimeout(() => {
if (current > 0) {
resolve({ value: current--, done: false });
} else {
resolve({ value: undefined, done: true });
}
}, 100);
});
},
return() {
console.log('cleanup ran');
return Promise.resolve({ value: undefined, done: true });
}
};
}
};
async function main() {
for await (const n of countdown) {
console.log(n); // 3, 2, 1 (100 ms apart)
}
for await (const n of countdown) {
console.log('first only:', n); // 3
break; // triggers return(): "cleanup ran"
}
}
main();Some things to notice:
this.fromis read inside[Symbol.asyncIterator](), so every loop gets a freshcurrent. That is why the second loop starts at 3 again.return()is optional. The loop calls it only when it exits early throughbreak,return, or an exception. When the iterator runs todone: trueon its own,return()is not called.- You can drive the iterator yourself, with no loop at all:
async function manual() {
const it = countdown[Symbol.asyncIterator]();
console.log(await it.next()); // { value: 3, done: false }
console.log(await it.next()); // { value: 2, done: false }
}
manual();Async Generators: The Usual Way
Hand-written iterators are verbose and easy to get wrong. An async generator (async function*) builds the protocol for you. Inside it you can use both await and yield. Each next() call resumes the function until the next yield and resolves its promise with that value.
Paginated APIs are the standard use case. The consumer wants a flat stream of items, and the generator hides the page fetching:
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
// Simulated API: three pages, each fetched with a delay.
async function fetchPage(page) {
await sleep(50);
const pages = { 1: ['a', 'b'], 2: ['c', 'd'], 3: ['e'] };
return {
items: pages[page] ?? [],
nextPage: page < 3 ? page + 1 : null
};
}
class PagedResource {
async *[Symbol.asyncIterator]() {
let page = 1;
try {
while (page !== null) {
console.log(`fetching page ${page}`);
const { items, nextPage } = await fetchPage(page);
yield* items; // delegate to the array, one item at a time
page = nextPage;
}
} finally {
console.log('connection closed');
}
}
}
async function main() {
for await (const item of new PagedResource()) {
console.log(item);
if (item === 'c') break;
}
}
main();
// fetching page 1
// a
// b
// fetching page 2
// c
// connection closedThis is lazy. Page 3 is never fetched because the loop stopped at 'c'. On break, the generator's built-in return() method resumes the generator as if a return statement stood at the paused yield, so the finally block runs. Put cleanup such as closing connections or releasing locks in finally, and it will run however the consumer leaves the loop.
Errors and Rejections
When the promise from next() rejects, for await throws at the loop. A normal try/catch handles it:
async function* flaky() {
yield 1;
throw new Error('network down');
}
async function main() {
try {
for await (const n of flaky()) {
console.log(n); // 1
}
} catch (e) {
console.log('caught:', e.message); // caught: network down
}
}
main();When the iterator itself fails, the loop does not call return(). The iterator is already finished, so there is nothing left to clean up. When the loop body throws, the loop does call return() before the error propagates.
The Sync Fallback
for await...of first looks for Symbol.asyncIterator. If there is none, it falls back to Symbol.iterator and wraps that sync iterator so that each value is awaited. That is why for await works on plain arrays, including arrays of promises:
const sleep = (ms, v) => new Promise((resolve) => setTimeout(() => resolve(v), ms));
async function main() {
for await (const v of [sleep(30, 'x'), 'y', sleep(10, 'z')]) {
console.log(v); // x, y, z (in array order, not resolution order)
}
}
main();| Object has | What `for await` uses |
|---|---|
| `Symbol.asyncIterator` | The async iterator, directly |
| Only `Symbol.iterator` | The sync iterator, with each value awaited |
| Neither | Throws `TypeError: ... is not async iterable` |
Common Errors
Using for await outside an async context. for await is only valid inside an async function or at the top level of an ES module. In a CommonJS script or a plain function it is a SyntaxError. Wrap the loop in an async function main(), as the examples here do.
Expecting spread or plain for...of to work. [...asyncIterable] and for (const x of asyncIterable) look for Symbol.iterator, not Symbol.asyncIterator, and throw a TypeError. To collect values into an array, use Array.fromAsync (ES2024, available in Node.js 22 and current browsers) or write a loop:
async function* letters() {
yield 'a';
yield 'b';
}
async function main() {
const viaHelper = await Array.fromAsync(letters());
console.log(viaHelper); // ['a', 'b']
const viaLoop = [];
for await (const l of letters()) viaLoop.push(l);
console.log(viaLoop); // ['a', 'b']
}
main();Forgetting that async iterables are sequential. for await waits for each body to finish before calling next() again. A slow body slows the whole stream, and a generator that awaits a network call for each item makes those calls one at a time. That is usually what you want for backpressure, meaning the producer never gets ahead of the consumer. When you want throughput instead, batch the work and use Promise.all on each batch.
Reusing a generator object. Calling an async generator function returns an object that is both the iterable and its own iterator. Once a loop consumes it or breaks out of it, it is finished, and a second loop over the same object yields nothing. Defining the generator as the [Symbol.asyncIterator] method, as PagedResource does, gives each loop a fresh generator.
Where You Meet It in Practice
You often consume async iterables you never wrote. Node.js readable streams, readline interfaces, and fs.promises.opendir directory handles are async iterable. So are web ReadableStream objects in current browsers and Node.js. All of them work with for await because they define Symbol.asyncIterator, the same hook your own classes use.
Exercise
You write const results = [...new PagedResource()]; using the class from this chapter. What happens, and how do you fix it?
Show answer
It throws a TypeError, because spread syntax looks for Symbol.iterator and PagedResource defines only Symbol.asyncIterator. Inside an async function, use const results = await Array.fromAsync(new PagedResource()); or push each item into an array inside a for await...of loop.
Exercise
Write an async generator ticks(n, ms) that yields the numbers 1 to n with a delay of ms milliseconds before each one, and logs "stopped" however iteration ends. Show a loop that stops after the second tick.
Show answer
const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); async function* ticks(n, ms) { try { for (let i = 1; i <= n; i++) { await sleep(ms); yield i; } } finally { console.log('stopped'); } } async function main() { for await (const t of ticks(5, 100)) { console.log(t); if (t === 2) break; } } main(); This prints 1, 2, then "stopped". The break calls the generator's return(), which runs the finally block.
Exercise
An object has both a Symbol.iterator method and a Symbol.asyncIterator method. Which one does for await...of use, and which one does for...of use?
Show answer
for await...of uses Symbol.asyncIterator and only falls back to Symbol.iterator when Symbol.asyncIterator is missing. for...of always uses Symbol.iterator and ignores Symbol.asyncIterator.