Sub topic 1
Refresher: How Iteration Works in JavaScript
Async iteration builds directly on the ordinary, synchronous iteration protocol. Before adding promises, you need a clear picture of what for...of does with an object. This chapter reviews that model so the async version in the next chapter reads as a small extension.
Prerequisites
This chapter assumes you are comfortable with:
- JavaScript functions, objects, and arrays
- Basic
for...ofloops - Running scripts in Node.js or a browser console
Promises and async/await are not needed yet. They become essential from the next chapter on.
Two roles: iterable and iterator
The iteration protocol defines two separate roles that are easy to confuse.
| Role | What it is | Required member |
|---|---|---|
| Iterable | An object that can produce an iterator | A method under the key `Symbol.iterator` |
| Iterator | An object that hands out values one at a time | A `next()` method |
| Iterator result | What each `next()` call returns | `{ value, done }` |
Symbol.iterator is a built-in symbol, a unique property key that the language reserves for this purpose. Arrays, strings, Map, and Set all have a Symbol.iterator method, so they are iterable.
Each call to next() returns an iterator result. When done is false, value holds the next item. When done is true, the sequence is over and value is usually ignored.
What for...of actually does
A for...of loop runs these steps:
- It calls
obj[Symbol.iterator]()once to get an iterator. - It calls
iterator.next(). - If the result has
done: true, it stops. - Otherwise it binds
result.valueto the loop variable, runs the body, and goes back to step 2.
A hand-written iterable
Here is an iterable range that follows the protocol with no shortcuts:
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
}Each call to range[Symbol.iterator]() creates a fresh iterator with its own current counter. That is why you can loop over range twice and get 1, 2, 3 both times. The iterable is reusable, while each iterator is used once and then finished.
You can also drive the iterator by hand to see the raw results:
const it = range[Symbol.iterator]();
console.log(it.next()); // { value: 1, done: false }
console.log(it.next()); // { value: 2, done: false }
console.log(it.next()); // { value: 3, done: false }
console.log(it.next()); // { value: undefined, done: true }Spread syntax ([...range]), destructuring (const [a, b] = range), and Array.from(range) all use the same protocol.
Common mistakes
- Returning the wrong shape.
next()must return an object such as{ value: 1, done: false }, not the bare value1. If it returns a primitive,for...ofthrows aTypeError. - Forgetting
done: true. Ifnext()never reportsdone: true, the loop never ends. - Treating an iterator as reusable. Once an iterator reports
done: true, it stays finished. CallSymbol.iteratoragain to start over. - Assuming plain objects are iterable.
for (const x of { a: 1 })throwsTypeError: ... is not iterable. UseObject.entries()instead.
Exercise
Write an iterable object evens whose iterator yields 2, 4, 6, 8 and then finishes, so that console.log([...evens]) prints [2, 4, 6, 8].
Show answer
const evens = { [Symbol.iterator]() { let n = 0; return { next() { n += 2; return n <= 8 ? { value: n, done: false } : { value: undefined, done: true }; } }; } }; Spread calls Symbol.iterator, then calls next() until done is true, and collects each value.
Exercise
Why does looping over range twice print 1, 2, 3 both times, while looping twice over the same iterator it (after giving it a [Symbol.iterator]() { return this; } method) prints nothing the second time?
Show answer
Each for...of over range calls range[Symbol.iterator]() and gets a new iterator with a fresh counter. An iterator that returns itself from Symbol.iterator keeps its state, so once it has reported done: true it stays exhausted.