Sub topic 2
The Async Iteration Protocol
This chapter assumes you know how Promise and async/await work, and that you remember the sync iteration protocol from the previous chapter: Symbol.iterator, next(), and { value, done } result objects. Here you will see how JavaScript extends that protocol to values that arrive over time.
Why the sync protocol is not enough
A sync iterator's next() must return { value, done } right away. That works for arrays and ranges, where the next value is already known. It does not work when the next value depends on a network response, a file read, or a timer.
You could have a sync iterator return promises as its values. The done flag would still have to be decided synchronously. The iterator would need to know whether more data exists before the data has arrived. A paginated API, for example, only tells you there is no next page after you fetch the current one.
The async iteration protocol solves this by making next() return a promise for the whole result object. Both value and done are settled later.
The two interfaces
The protocol defines two roles, in the same way the sync protocol does:
- An async iterable is an object with a method under the key
Symbol.asyncIterator. Calling that method returns an async iterator. - An async iterator is an object with a
next()method that returns aPromiseresolving to{ value, done }.
An async iterator may also have optional return() and throw() methods. A later chapter covers them along with early exit.
| Aspect | Sync protocol | Async protocol |
|---|---|---|
| Entry method key | `Symbol.iterator` | `Symbol.asyncIterator` |
| `next()` returns | `{ value, done }` | `Promise<{ value, done }>` |
| When `done` is known | Immediately | When the promise resolves |
| Consuming loop | `for...of` | `for await...of` |
| Generator syntax | `function*` | `async function*` |
Driving the protocol by hand
The for await...of loop calls these methods for you. Calling them yourself once shows what the loop does.
const delayedNumbers = {
[Symbol.asyncIterator]() {
let n = 0;
return {
next() {
const current = ++n;
return new Promise((resolve) => {
setTimeout(() => {
resolve(
current <= 3
? { value: current, done: false }
: { value: undefined, done: true }
);
}, 100);
});
}
};
}
};
async function main() {
const iterator = delayedNumbers[Symbol.asyncIterator]();
let result = await iterator.next();
while (!result.done) {
console.log(result.value); // 1, 2, 3, about 100 ms apart
result = await iterator.next();
}
console.log('finished');
}
main();The consumer awaits each next() before it asks for another one. This pull-based, one-at-a-time rhythm is the core of async iteration. The producer does the work for an item only when someone asks for it.
Common errors
- Returning a plain object from
next(). The protocol requires a promise.awaitwill tolerate a plain object, but other consumers that call.then()on the result will break. ReturnPromise.resolve({ value, done })when the result is ready immediately. - Resolving with the value instead of a result object.
resolve(42)is wrong. Useresolve({ value: 42, done: false }). Withoutdone, a consumer reads the result as unfinished withvalueundefined. - Rejecting to signal the end. A rejected promise means an error. A normal end is a resolved
{ done: true }. - Calling
next()again before the previous promise settles. Hand-written iterators like the one above do not queue overlapping calls safely. Async generators do queue them.
To check whether a value is async iterable, test the method:
const isAsyncIterable = (obj) =>
obj != null && typeof obj[Symbol.asyncIterator] === 'function';
console.log(isAsyncIterable({ [Symbol.asyncIterator]() {} })); // true
console.log(isAsyncIterable([1, 2, 3])); // falseExercise
A sync iterator can return { value: somePromise, done: false }. What can an async iterator do that this approach cannot, and which part of the result object makes the difference?
Show answer
An async iterator can decide whether the sequence is finished after asynchronous work completes, because the whole result object, including done, is delivered through a promise. A sync iterator must set done immediately, before it knows whether more data exists.
Exercise
Fix this iterator method so it follows the protocol: next() { return new Promise((r) => setTimeout(() => r(7), 50)); }
Show answer
Resolve with a result object: next() { return new Promise((r) => setTimeout(() => r({ value: 7, done: false }), 50)); }. To end the sequence, it should eventually resolve with { value: undefined, done: true }.