Sub topic 8
Async Iteration with Symbol.asyncIterator
This chapter assumes you already know how Symbol.iterator and the iteration protocol work. It also assumes you are comfortable with Promises, async/await, and generator functions. Here you will learn the async version of the protocol. In it, each value can arrive later, for example from a timer, a network stream, or a paginated API.
The Async Iteration Protocol
An object is async iterable when it has a method under the Symbol.asyncIterator key. That method returns an async iterator, which is an object whose next() method returns a Promise that resolves to { value, done }.
The sync protocol differs in one place. A sync next() returns the result object directly. An async next() returns a Promise of that result object. The consumer is for await...of, which awaits each Promise before it runs the loop body.
Implementing the Protocol by Hand
Writing the protocol out yourself shows every moving part:
const countdown = {
from: 3,
[Symbol.asyncIterator]() {
let current = this.from;
return {
next() {
return new Promise((resolve) => {
setTimeout(() => {
if (current > 0) {
resolve({ value: current--, done: false });
} else {
resolve({ value: undefined, done: true });
}
}, 100);
});
}
};
}
};
(async () => {
for await (const n of countdown) {
console.log(n); // 3, 2, 1 (100 ms apart)
}
console.log('Liftoff');
})();The Usual Way: Async Generators
Most of the time you will write an async * generator method instead. It handles the Promise wrapping and the { value, done } objects for you, and you can use await inside it:
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
class Poller {
constructor(times) {
this.times = times;
}
async *[Symbol.asyncIterator]() {
try {
for (let i = 1; i <= this.times; i++) {
await sleep(50);
yield `tick ${i}`;
}
} finally {
console.log('poller cleaned up');
}
}
}
(async () => {
for await (const msg of new Poller(5)) {
console.log(msg);
if (msg === 'tick 2') break;
}
})();
// tick 1
// tick 2
// poller cleaned upWhen the loop exits early through break, return, or a thrown error, for await...of calls the iterator's return() method. For a generator, that call runs the finally block. Put cleanup code there, such as closing connections or clearing timers.
Common Errors
| Mistake | What happens | Fix |
|---|---|---|
| Using `for...of` on an async-only iterable | `TypeError: ... is not iterable` | Use `for await...of` |
| Using `for await` in a plain function | `SyntaxError` | Put it in an `async` function or at the top level of a module |
| Defining `Symbol.asyncIterator` as a regular sync generator | Promises are yielded but the protocol shape is wrong | Use `async *` |
| Expecting the loop to run iterations in parallel | Each `next()` waits for the previous one | Use `Promise.all` when you need concurrency |
Exercise
Write an object pages whose Symbol.asyncIterator is an async generator that yields the arrays [1, 2], [3, 4], and [5], each after a 10 ms delay. Then log every number with nested loops.
Show answer
const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); const pages = { async *[Symbol.asyncIterator]() { for (const page of [[1, 2], [3, 4], [5]]) { await sleep(10); yield page; } } }; (async () => { for await (const page of pages) { for (const n of page) console.log(n); } })(); // logs 1, 2, 3, 4, 5
Exercise
In the Poller example, why does "poller cleaned up" print even though the loop exits with break before the generator finishes?
Show answer
When the loop exits early, for await...of calls the async iterator's return() method. In a generator, return() resumes it as if a return statement ran at the paused yield. That runs the finally block before the generator closes.