Sub topic 7
Building an Async Iterable by Hand
This chapter assumes you know the sync iteration protocol, the for await...of loop, and async generators from earlier chapters. You should also be comfortable with Promises and setTimeout.
An async generator is usually the easiest way to produce an async sequence. Writing the protocol by hand still pays off. It shows exactly what for await...of asks of an object, and it lets you wrap event-based or callback-based sources that don't fit neatly into a generator.
The contract you must satisfy
An object is async iterable when it has a method under the key Symbol.asyncIterator. That method returns an async iterator: an object with these methods.
| Method | Required | Returns | Called by `for await...of` when |
|---|---|---|---|
| `next()` | Yes | Promise of `{ value, done }` | Each loop step |
| `return()` | No | Promise of `{ value, done }` | The loop exits early (`break`, `return`, or a throw in the body) |
| `throw()` | No | Promise of `{ value, done }` | Never; only manual callers use it |
The loop calls next(), awaits the Promise, and checks done. If done is false, the loop runs its body with value. If done is true, the loop stops without calling return().
A worked example: a ticker
const ticker = {
[Symbol.asyncIterator]() {
let count = 0;
return {
next() {
count++;
if (count > 3) {
return Promise.resolve({ value: undefined, done: true });
}
return new Promise((resolve) =>
setTimeout(() => resolve({ value: count, done: false }), 100)
);
},
return() {
console.log('cleanup');
return Promise.resolve({ value: undefined, done: true });
}
};
}
};
async function main() {
for await (const tick of ticker) {
console.log(tick);
if (tick === 2) break; // calls return(), logs 'cleanup'
}
}
main();Running this prints 1, 2, then cleanup. If you remove the break, the loop prints 1, 2, 3, and cleanup never appears. Normal completion does not call return().
The state (count) lives inside [Symbol.asyncIterator](), so each loop over ticker gets a fresh iterator and starts again at 1.
Common mistakes
Putting state on the iterable instead of the iterator
If count were a property of ticker, a second loop would see count > 3 straight away and finish immediately. Keep per-iteration state inside the factory method unless you really want a one-shot source.
Expecting `value` to be awaited
A real async iterator's value is passed to the loop body as it is. If you resolve { value: somePromise, done: false }, the loop variable is the Promise itself, not its result. Resolve the outer Promise with the final value instead.
Returning a non-object from `next()`
next() must resolve to an object. If it resolves to a number or undefined, the loop throws a TypeError.
Overlapping `next()` calls
for await...of always waits for one next() to settle before calling it again. Other callers might not. For example, someone could call it.next() twice in a row and then use Promise.all on the results. Async generators queue those calls for you. A hand-written iterator has to handle them itself, or else document that it doesn't. This is one reason to prefer async function* unless you need the extra control.
Forgetting cleanup in `return()`
If your iterator holds a timer, socket, or listener, release it in return(). That is the only hook you get when a consumer breaks out early.
Exercise
Change the ticker so that each call to ticker[Symbol.asyncIterator]() accepts no arguments but the object has a limit property (default 3) that the iterator respects. Then explain what happens if two for await...of loops run over ticker at the same time.
Show answer
Add limit: 3 to the object, capture const limit = this.limit; inside [Symbol.asyncIterator](), and replace count > 3 with count > limit. Because count and limit live in the closure created by each [Symbol.asyncIterator]() call, two concurrent loops each get their own iterator and each count 1 to limit on its own, without affecting the other.
Exercise
An iterator's next() returns Promise.resolve({ value: fetch(url), done: false }). What is the type of the loop variable inside for await...of, and how do you fix it?
Show answer
The loop variable is a Promise (the pending fetch result), because async iterators' values are not awaited. Fix it by awaiting inside next(), for example async next() { return { value: await fetch(url), done: false }; }.