Sub topic 16
Async Iteration with for await...of
The earlier chapters covered synchronous iteration. In that model, next() returns { value, done } right away, and for...of reads one result after another. Many data sources can't work that way because they deliver values over time: network responses, file chunks, database cursors, and message queues. This chapter covers the async version of the protocols. It shows how Symbol.asyncIterator and a promise-returning next() let for await...of wait for each value before it runs the loop body.
This chapter assumes you know the iterable and iterator protocols, custom iterables, and return() cleanup from earlier chapters. It also assumes you are comfortable with promises and async/await. Async generators, which are the short way to write async iterators, get their own chapter next. This chapter builds async iterators by hand so you can see how the protocol works.
The Async Iteration Protocols
The async protocols mirror the sync ones and change two things:
- The async iterable protocol. An object is async iterable if it has a method under the key
Symbol.asyncIteratorthat returns an async iterator. - The async iterator protocol. An async iterator has a
next()method that returns a promise of{ value, done }, not the result object itself. The optionalreturn()andthrow()methods also return promises.
| Aspect | Sync iterator | Async iterator |
|---|---|---|
| Entry point | `obj[Symbol.iterator]()` | `obj[Symbol.asyncIterator]()` |
| `next()` returns | `{ value, done }` | `Promise<{ value, done }>` |
| `return()` returns | `{ value, done }` | `Promise<{ value, done }>` |
| Consumed by | `for...of`, spread, destructuring, `Array.from` | `for await...of`, `Array.fromAsync` |
| `done` known | Immediately | When the promise settles |
The promise wraps the whole result object, done included. The consumer can't know whether the sequence has ended until that promise settles. This is the main difference from a sync iterator that yields promises, which a later section covers.
Building an Async Iterable by Hand
The following object counts down from 3 and waits 100 ms before producing each number. Its next() is an async method, so it always returns a promise.
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const countdown = {
from: 3,
[Symbol.asyncIterator]() {
let current = this.from;
return {
async next() {
await sleep(100);
if (current > 0) {
return { value: current--, done: false };
}
return { value: undefined, done: true };
},
async return() {
console.log('stopped early');
return { value: undefined, done: true };
}
};
}
};
(async () => {
for await (const n of countdown) {
console.log(n); // 3, 2, 1, about 100 ms apart
}
console.log('finished');
})();The loop finishes normally here, so return() is never called and "stopped early" never prints. As with sync iterators, return() runs only on early exit.
Stepping Through Manually
Calling next() by hand shows that each result arrives as a promise that has to be awaited:
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const countdown = {
from: 2,
[Symbol.asyncIterator]() {
let current = this.from;
return {
async next() {
await sleep(50);
return current > 0
? { value: current--, done: false }
: { value: undefined, done: true };
}
};
}
};
(async () => {
const it = countdown[Symbol.asyncIterator]();
const pending = it.next();
console.log(pending instanceof Promise); // true
console.log(await pending); // { value: 2, done: false }
console.log(await it.next()); // { value: 1, done: false }
console.log(await it.next()); // { value: undefined, done: true }
})();How for await...of Runs
On each pass, for await...of calls next(), awaits the promise, checks done, and then runs the body with value. The body runs to completion, including any await inside it, before the loop calls next() again. Items are therefore processed one at a time, in order.
You can use for await...of only inside an async function or at the top level of an ES module. In a CommonJS script or a regular function, it is a syntax error.
for await...of Over Sync Iterables
If the object has no Symbol.asyncIterator, for await...of falls back to Symbol.iterator and awaits each value it yields. This lets you loop over an array of promises:
const delayed = (value, ms) =>
new Promise(resolve => setTimeout(() => resolve(value), ms));
(async () => {
const items = [delayed('slow', 200), delayed('fast', 50), 'plain'];
for await (const v of items) {
console.log(v); // slow, fast, plain (array order, not settle order)
}
})();Values arrive in iteration order. The loop waits for 'slow' even though 'fast' settled first. Non-promise values like 'plain' are passed through unchanged.
Early Exit, Errors, and Cleanup
Cleanup works much as it does in the sync case, except that return() is awaited:
break,return, or athrowinside the loop body makes the loop call the iterator'sreturn()and wait for its promise before moving on.- A rejected
next()promise makes the loop throw that error at thefor awaitline. The loop treats the iterator as broken and does not callreturn().
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
function source(failAt) {
let i = 0;
return {
[Symbol.asyncIterator]() {
return this;
},
async next() {
await sleep(20);
i++;
if (i === failAt) throw new Error(`source failed at ${i}`);
return { value: i, done: false };
},
async return() {
await sleep(20); // simulate closing a connection
console.log('cleanup');
return { value: undefined, done: true };
}
};
}
(async () => {
for await (const n of source(Infinity)) {
if (n === 2) break; // awaits return(): logs 'cleanup'
}
console.log('after break');
try {
for await (const n of source(3)) {
console.log('got', n); // got 1, got 2
}
} catch (err) {
console.log(err.message); // source failed at 3 (no 'cleanup')
}
})();Expected output, in order: cleanup, after break, got 1, got 2, source failed at 3. Because the break waits for return(), "after break" never prints before the connection has closed. If your iterator holds a resource, make next() release it before it rejects, because nothing else will call return() in that case.
Async Iterables in the Platform
You'll often consume async iterables that other code provides:
| Source | Environment | What each value is |
|---|---|---|
| `ReadableStream` | Modern browsers, Node.js 18+, Deno | A chunk of the stream |
| `stream.Readable` (e.g. `fs.createReadStream`) | Node.js | A `Buffer` or string chunk |
| `readline.createInterface({ input })` | Node.js | One line of text |
| `events.on(emitter, name)` | Node.js | The arguments array of each event |
Browsers added async iteration of ReadableStream later than other runtimes, so check support before you rely on it in browser code. The Node.js example below reads a file line by line, and memory use stays flat because only one chunk is in memory at a time:
import { createReadStream } from 'node:fs';
import { createInterface } from 'node:readline';
import { writeFile } from 'node:fs/promises';
await writeFile('demo.txt', 'alpha\nbeta\ngamma\n');
const rl = createInterface({ input: createReadStream('demo.txt') });
let count = 0;
for await (const line of rl) {
count++;
console.log(count, line); // 1 alpha, 2 beta, 3 gamma
}Save it as lines.mjs so that top-level await is allowed.
To collect a whole async iterable into an array, Array.fromAsync(iterable) returns a promise of the array. It is available in current browsers and Node.js 22+. Spread ([...x]) and Array.from work only with sync iterables.
Common Errors
- Using
for...ofon an async-only iterable. It throwsTypeError: ... is not iterablebecauseSymbol.iteratoris missing. - Forgetting that
next()must return a promise. If a hand-writtennext()returns a plain object,for awaitstill works because it awaits the result anyway. The code then breaks for anyone who callsawait it.next()expecting the contract. Make the methodasync. - Resolving the promise with the value instead of
{ value, done }. The loop readsdonefrom whatever the promise resolves to, soresolve(42)givesundefinedvalues and the loop never ends. - Expecting parallelism.
for await...ofnever starts the nextnext()until the body finishes.
Exercise
An object has a method under Symbol.asyncIterator, and its next() method is async and returns { value: n, done: false } forever. A for await...of loop over it hits break on the third value. List, in order, the protocol methods the loop calls and say what it waits for at each step.
Show answer
The loop calls obj[Symbol.asyncIterator]() once to get the iterator. It then calls next() three times and awaits each returned promise before running the body. On break it calls return() and awaits that promise as well, and only then does the code after the loop run.
Exercise
Why can for await (const r of [fetchA(), fetchB()]) produce an unhandled promise rejection when a hand-written async iterator that calls fetchA and fetchB inside next() does not?
Show answer
The array expression starts both requests before the loop begins. If fetchB() rejects while the loop is still awaiting fetchA(), no handler is attached to fetchB's promise yet, so the runtime reports an unhandled rejection. The async iterator creates each promise only when next() is called, and the loop awaits it right away, so a handler is always attached.
Exercise
Write an async iterable ticker(n, ms) by hand (no generators) that yields 0 through n - 1, waiting ms milliseconds before each value, and logs 'ticker closed' if the consumer exits early.
Show answer
function ticker(n, ms) { let i = 0; return { [Symbol.asyncIterator]() { return this; }, async next() { await new Promise(r => setTimeout(r, ms)); return i < n ? { value: i++, done: false } : { value: undefined, done: true }; }, async return() { console.log('ticker closed'); return { value: undefined, done: true }; } }; } Using it in for await (const t of ticker(5, 100)) { if (t === 1) break; } logs 'ticker closed'.