Sub topic 1
Refresher: How Iteration Works in JavaScript
Prerequisites
This chapter assumes you know JavaScript functions, objects, and arrays. It also assumes you can use Promises with async/await, write basic for...of loops, and run scripts in Node.js or a browser console.
The Sync Iteration Protocol
An object is iterable if it has a [Symbol.iterator]() method. That method returns an iterator, which is an object whose next() method returns { value, done }. The for...of loop calls next() repeatedly until done is true.
const range = {
from: 1,
to: 3,
[Symbol.iterator]() {
let current = this.from;
const last = this.to;
return {
next() {
return current <= last
? { value: current++, done: false }
: { value: undefined, done: true };
}
};
}
};
for (const n of range) {
console.log(n); // 1, 2, 3
}The Async Iteration Protocol
The async protocol has the same structure with two changes:
| Aspect | Sync | Async |
|---|---|---|
| Method key | `Symbol.iterator` | `Symbol.asyncIterator` |
| `next()` returns | `{ value, done }` | `Promise<{ value, done }>` |
| Consumer | `for...of` | `for await...of` |
Because next() returns a Promise, the consumer has to wait for each result to settle before it knows whether the sequence has ended.
Consuming with for await...of
You can use for await...of only inside an async function or at the top level of an ES module. A common mistake is putting it in a regular function, which causes a SyntaxError. The loop pauses on each value, so its body runs once per value, in order.
Producing with async function*
An async generator (async function*) is the simplest way to build an async iterable. Inside it you can await and also yield. Each yield resolves one next() Promise.
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function* countdown(from) {
for (let i = from; i > 0; i--) {
await sleep(100);
yield i;
}
}
async function main() {
for await (const n of countdown(3)) {
console.log(n); // 3, 2, 1, about 100 ms apart
}
}
main();Exercise
You call countdown(3).next() directly. What does it return, and how do you get the number 3 out of it?
Show answer
It returns a Promise that resolves to { value: 3, done: false }. Await it and read the value: (await countdown(3).next()).value.
Exercise
Why does function run() { for await (const n of countdown(2)) {} } fail?
Show answer
for await...of is only allowed inside an async function or at the top level of a module. Declaring run as async function run() fixes it.