Sub topic 2
The Async Iteration Protocol
This chapter assumes you know JavaScript objects and functions, can read Promise and async/await code, and remember the sync iteration protocol from the previous chapter. In that protocol, [Symbol.iterator]() returns an iterator, and the iterator's next() returns { value, done }. Here you will see how JavaScript extends that contract to values that arrive over time, and why the change matters.
Why the sync protocol is not enough
The sync protocol requires next() to return its answer immediately. The caller gets back a { value, done } object in the same tick, with no waiting. That works for arrays, strings, Maps, and generators that compute values in memory. It fails for data that has not arrived yet, such as the next chunk of a network response, the next line of a file, or the next message on a socket.
The obvious workaround is a sync iterable whose values are Promises:
const delays = [300, 100];
const promises = delays.map(
(ms) => new Promise((resolve) => setTimeout(() => resolve(ms), ms))
);
for (const p of promises) {
console.log(p); // Promise { <pending> } (twice)
}Each value can now be resolved later, but done is still synchronous. The iterator has to know right away whether another item exists. That is fine when you know the number of items in advance, as with two timers. It breaks when the end of the sequence is itself unknown. A paginated API only tells you there is no next page after you fetch the current one. A stream only knows it is finished when the underlying source closes. The sync protocol has no way to say "I'll tell you later whether there is more."
The contract
The async iteration protocol fixes this by making the whole result asynchronous, not just the value. Two definitions:
- 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 whose
next()method returns a Promise that resolves to an iterator result object{ value, done }.
Symbol.asyncIterator is a well-known symbol, a built-in symbol the language itself looks up. It was added in ES2018 together with for await...of and async generators, and every current browser and Node.js release supports it.
| Aspect | Sync protocol | Async protocol |
|---|---|---|
| Method key on the iterable | `Symbol.iterator` | `Symbol.asyncIterator` |
| `next()` returns | `{ value, done }` | `Promise<{ value, done }>` |
| When `done` is known | Immediately | When the Promise settles |
| Optional `return(value)` | Returns `{ value, done }` | Returns `Promise<{ value, done }>` |
| Optional `throw(err)` | Returns `{ value, done }` or throws | Returns a Promise, possibly rejected |
| Built-in consumer | `for...of`, spread, destructuring | `for await...of`, `Array.fromAsync` |
| Generator syntax | `function*` | `async function*` |
The optional return() and throw() methods mirror their sync counterparts. Consumers call return() to signal that they are finished early, so the iterator can release resources. throw() injects an error into the iterator and is mostly relevant to generators. Later chapters cover both in detail. For now, remember that if they exist, they also return Promises.
Driving the protocol by hand
for await...of, covered in the next chapter, runs this whole sequence for you. To see the protocol itself, call the methods directly. The example below builds a minimal async iterable that delivers two items, 50 ms apart:
const source = {
[Symbol.asyncIterator]() {
const items = ['a', 'b'];
let i = 0;
return {
next() {
return new Promise((resolve) => {
setTimeout(() => {
if (i < items.length) {
resolve({ value: items[i++], done: false });
} else {
resolve({ value: undefined, done: true });
}
}, 50);
});
}
};
}
};
async function main() {
const it = source[Symbol.asyncIterator]();
let result = await it.next();
while (!result.done) {
console.log(result.value); // 'a', then 'b'
result = await it.next();
}
console.log('finished');
}
main();The loop follows the protocol step by step:
- It gets an iterator by calling the iterable's
Symbol.asyncIteratormethod. - It calls
next()and awaits the Promise. - It reads
doneonly after the Promise settles. This is the key difference from the sync protocol. - It repeats until
doneistrue.
The final call checks the item count only after the timer fires. A real source can make that decision at that point, for example after a fetch reports that there is no next page.
Iterable versus iterator
Keep the two roles separate. The iterable is the thing you can loop over. The iterator is the cursor that tracks your position. In source above they are different objects, so each call to source[Symbol.asyncIterator]() creates a fresh cursor that starts from the beginning.
Many built-in async iterators are also iterables, because their Symbol.asyncIterator method returns this. Async generator objects work this way, and so do Node.js readable streams. That design lets you pass an iterator anywhere an iterable is expected. It also means the sequence can only be consumed once: a second loop over the same object continues from wherever the first one stopped, or receives nothing if the first loop finished.
async function* letters() {
yield 'x';
yield 'y';
}
const gen = letters();
console.log(gen[Symbol.asyncIterator]() === gen); // trueChecking whether something is async iterable
There is no isAsyncIterable built in. Test for the method:
function isAsyncIterable(obj) {
return obj != null && typeof obj[Symbol.asyncIterator] === 'function';
}
function isSyncIterable(obj) {
return obj != null && typeof obj[Symbol.iterator] === 'function';
}
console.log(isAsyncIterable([1, 2])); // false
console.log(isSyncIterable([1, 2])); // true
console.log(isAsyncIterable((async function* () {})())); // trueLibrary code often accepts either kind and prefers the async path when both are present. for await...of follows the same rule: it looks for Symbol.asyncIterator first and only falls back to Symbol.iterator if that is missing. A later chapter covers that fallback.
Common mistakes and gotchas
Defining Symbol.iterator when you meant Symbol.asyncIterator
If your next() returns Promises but you put it under Symbol.iterator, a plain for...of treats each Promise object as the full result. It reads done from the Promise object, gets undefined, which is falsy, and loops forever while logging undefined values. Use the async key whenever next() is asynchronous.
Returning a non-object from next()
The resolved value of next() must be an object. If it resolves to undefined or a number, consumers such as for await...of throw TypeError: Iterator result undefined is not an object. This mistake is common in hand-written iterators when one branch forgets to resolve with a result object, or resolves with the raw value.
Expecting value to be unwrapped
A real async iterator delivers value exactly as you resolved it. If value is itself a Promise, the consumer receives a Promise:
const odd = {
[Symbol.asyncIterator]() {
let sent = false;
return {
next() {
if (sent) return Promise.resolve({ value: undefined, done: true });
sent = true;
return Promise.resolve({ value: Promise.resolve(42), done: false });
}
};
}
};
async function main() {
for await (const v of odd) {
console.log(v); // Promise { 42 }, not 42
}
}
main();Async generators are different. yield somePromise awaits the Promise before delivering it, so consumers of generators always get settled values. Hand-written iterators should follow the same rule and resolve with plain values, not with Promises nested inside the result.
Calling next() again before the previous call settles
The protocol does not forbid overlapping calls. A consumer may call next() twice without awaiting the first. Async generators queue these requests and answer them in order. A hand-written iterator that shares mutable state between pending calls can deliver items out of order, or deliver the same item twice. for await...of never overlaps calls, because it awaits each result before asking for the next one. So the problem only appears when other code drives your iterator manually. If you write an iterator for others to use, either queue requests yourself or document that calls must not overlap.
Assuming the protocol makes things concurrent
An async iterator is pull-based: nothing new is requested until the consumer calls next(). Iterating is sequential by design. That suits sources where order matters or where each step depends on the previous one, such as pagination cursors. It is not a way to run independent tasks in parallel. A later chapter compares this pattern with Promise.all.
Exercises
Exercise
A sync iterable can yield Promises. Name the one piece of information that such an iterable cannot provide asynchronously, and give a data source where this matters.
Show answer
The done flag. A sync iterator must decide right away whether another item exists. For a paginated API, you only learn whether there is a next page after the current page's request completes, so the end of the sequence cannot be known up front.
Exercise
This object is meant to be async iterable, but for await...of throws "Iterator result 1 is not an object". What is wrong? { [Symbol.asyncIterator]() { let n = 0; return { next() { n++; return Promise.resolve(n <= 2 ? n : { done: true }); } }; } }
Show answer
For the first two calls, next() resolves to the bare number n instead of an iterator result object. It should resolve to { value: n, done: false }, and to { value: undefined, done: true } at the end.
Exercise
You call gen[Symbol.asyncIterator]() on an async generator object, loop over the result until it is done, and then loop over gen again. What does the second loop produce, and why?
Show answer
Nothing. An async generator's Symbol.asyncIterator method returns the generator itself, so both loops share one cursor. The first loop used up the sequence, and the second loop immediately receives done: true.
Exercise
Write an isAsyncIterable(obj) function that returns false for null and undefined instead of throwing.
Show answer
function isAsyncIterable(obj) { return obj != null && typeof obj[Symbol.asyncIterator] === 'function'; } The != null check covers both null and undefined before the property lookup.