Sub topic 16
Async Iteration with for await...of
This chapter assumes you know the iterator protocol from earlier chapters and are comfortable with promises and async/await.
The async iterator protocol
A regular iterator returns { value, done } from next() right away. That design breaks down when the next value isn't ready yet, for example a network response or a chunk from a file. Async iteration fixes this with one change: next() returns a promise that resolves to { value, done }.
The protocol mirrors the synchronous one:
| Synchronous | Asynchronous |
|---|---|
| `[Symbol.iterator]()` returns an iterator | `[Symbol.asyncIterator]()` returns an async iterator |
| `next()` returns `{ value, done }` | `next()` returns `Promise<{ value, done }>` |
| Consumed by `for...of` | Consumed by `for await...of` |
Writing an async iterable by hand
This countdown waits 100 ms before producing each number:
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const countdown = {
from: 3,
[Symbol.asyncIterator]() {
let n = this.from;
return {
async next() {
await sleep(100);
return n > 0
? { value: n--, done: false }
: { value: undefined, done: true };
}
};
}
};
(async () => {
for await (const n of countdown) {
console.log(n); // 3, 2, 1, about 100 ms apart
}
console.log('liftoff');
})();Because next is an async method, it returns a promise automatically. for await...of calls next(), waits for the promise to settle, and then runs the loop body with value. It repeats until a result has done: true.
for await...of with sync iterables
for await...of also accepts ordinary iterables. If the iterable has no Symbol.asyncIterator, the loop falls back to Symbol.iterator and awaits each value:
(async () => {
const items = [Promise.resolve('a'), 'b', Promise.resolve('c')];
for await (const x of items) {
console.log(x); // a, b, c
}
})();The loop still handles one item at a time. All the promises already exist, so their work may run at the same time, but the loop body sees the results in array order.
Common errors
- Using
for...ofon an async-only iterable.for (const n of countdown)throwsTypeError: countdown is not iterable, becausecountdownhas noSymbol.iterator. - Using
for awaitoutside an async context.for awaitis valid only inside anasyncfunction or at the top level of an ES module. - Expecting spread or destructuring to work.
[...countdown]throws too. Spread, destructuring, andArray.fromread only synchronous iterables. UseArray.fromAsync(countdown)(ES2024), which returns a promise of an array. Check that your target runtime supports it. - Expecting parallelism. Each
next()is awaited before the next one is requested, so the steps run one after another.
Exercise
A stream object defines only [Symbol.asyncIterator]. Which of these work: for (const x of stream), for await (const x of stream) inside an async function, [...stream], and await Array.fromAsync(stream)?
Show answer
Only for await...of and await Array.fromAsync(stream) work. for...of and spread look for Symbol.iterator, find none, and throw a TypeError.
Exercise
What does for await (const x of [1, Promise.resolve(2)]) console.log(x) log, and why doesn't it throw?
Show answer
It logs 1, then 2. The array has no Symbol.asyncIterator, so the loop uses Symbol.iterator and awaits each value. Awaiting a non-promise like 1 just gives back 1.