JavaScriptFundamental (ES6), part 2
Symbol.iterator vs Symbol.asyncIterator in JavaScript
18 When both iterator symbols are present
fairGive one object both a [Symbol.iterator] and a [Symbol.asyncIterator] that yield different values. Work out which one for...of, spread and for await each choose.
Stuck? Three hints, smallest first
- 1. Spread and
for...ofonly ever look atSymbol.iterator. - 2.
for awaitlooks forSymbol.asyncIteratorfirst and only falls back when it is absent. - 3. Make the two yield distinguishable values, so the answer is visible rather than argued about.
const both = {
[Symbol.iterator]() {
let i = 0;
return { next: () => (i < 2 ? { value: 'sync ' + i++, done: false } : { value: undefined, done: true }) };
},
[Symbol.asyncIterator]() {
let i = 0;
return {
next: () => Promise.resolve(i < 2 ? { value: 'async ' + i++, done: false } : { value: undefined, done: true }),
};
},
};
const collect = async (source) => {
const out = [];
for await (const v of source) out.push(v);
return out;
};
const spread = [...both];
const syncLoop = [];
for (const v of both) syncLoop.push(v);
const asyncLoop = await collect(both);
const syncOnly = await collect({ [Symbol.iterator]: both[Symbol.iterator] });
const neither = (() => { try { return [...{}]; } catch (e) { return e.constructor.name; } })();
console.log('spread :', spread);
console.log('for...of :', syncLoop);
console.log('for await :', asyncLoop, '<- the async one wins');
console.log('sync only, awaited:', syncOnly);
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('spread uses Symbol.iterator', spread, ['sync 0', 'sync 1']);
test('so does for...of', syncLoop, ['sync 0', 'sync 1']);
test('for await prefers Symbol.asyncIterator when it exists', asyncLoop, ['async 0', 'async 1']);
test('and falls back to the sync one when it does not', syncOnly, ['sync 0', 'sync 1']);
test('an object with neither is not iterable at all', neither, 'TypeError');
test('both symbols describe themselves by name', [String(Symbol.iterator), String(Symbol.asyncIterator)], ['Symbol(Symbol.iterator)', 'Symbol(Symbol.asyncIterator)']);
test('an async generator supplies only the async one', [typeof (async function* () {})()[Symbol.asyncIterator], typeof (async function* () {})()[Symbol.iterator]], ['function', 'undefined']);
test('a sync generator supplies only the sync one', [typeof (function* () {})()[Symbol.iterator], typeof (function* () {})()[Symbol.asyncIterator]], ['function', 'undefined']);
Two protocols, two keys, and the choice is made by the consumer, not the producer. That is why an object can offer both: a caller who can wait gets the async view, a caller who cannot gets the sync one. Node's streams do something close to this.
It is also a way to be quietly inconsistent. Nothing checks that the two agree, so an object whose sync iterator yields stale cached values and whose async iterator fetches fresh ones will behave differently depending on which loop you reach for, with nothing in the code to warn you. If you implement both, make them yield the same values or give them different names.
The fallback in the fourth assertion is worth remembering the other way round too: for await works on anything iterable, including an array or a string, so it is safe as the general-purpose loop when you do not know what you were handed. The cost is one microtask per element even when nothing is asynchronous.