JavaScriptFundamental (ES6), part 2
Implement Symbol.asyncIterator by hand in JavaScript
12 Symbol.asyncIterator, written by hand
hardGive a plain object a [Symbol.asyncIterator] whose next() returns promises, and drive it with for await...of. Then check what a plain for...of makes of it, and what for await does with an ordinary array of promises.
Stuck? Three hints, smallest first
- 1. The async protocol is the same two-property result object, wrapped in a promise.
- 2.
for...oflooks forSymbol.iteratoronly, so it will not accept an async-only object. - 3.
for awaitfalls back toSymbol.iteratorwhen there is no async one, awaiting each value it finds.
const tills = {
amounts: [1200, 3400, 800],
[Symbol.asyncIterator]() {
const amounts = this.amounts;
let i = 0;
return {
next() {
return i < amounts.length
? Promise.resolve({ value: amounts[i++], done: false })
: Promise.resolve({ value: undefined, done: true });
},
};
},
};
const collect = async (source) => {
const out = [];
for await (const value of source) out.push(value);
return out;
};
const seen = await collect(tills);
const syncRefused = (() => {
try { for (const x of tills) return 'looped ' + x; return 'empty'; }
catch (e) { return e.constructor.name; }
})();
const emptySource = { [Symbol.asyncIterator]: () => ({ next: () => Promise.resolve({ done: true }) }) };
console.log('for await gave:', seen, 'total', seen.reduce((a, b) => a + b, 0));
console.log('plain for...of :', syncRefused);
console.log('next() returns a promise?', typeof tills[Symbol.asyncIterator]().next().then);
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('for await...of drives the async iterator', seen, [1200, 3400, 800]);
test('each next() hands back a promise', typeof tills[Symbol.asyncIterator]().next().then, 'function');
test('a plain for...of refuses an async-only iterable', syncRefused, 'TypeError');
test('an empty async source loops zero times', await collect(emptySource), []);
test('for await also accepts a plain sync iterable', await collect([1, 2, 3]), [1, 2, 3]);
test('and awaits every value it finds there', await collect([Promise.resolve('a'), Promise.resolve('b')]), ['a', 'b']);
test('so a promise of a promise is unwrapped too', await collect([Promise.resolve(Promise.resolve('deep'))]), ['deep']);
test('the two symbols are different keys', Symbol.iterator === Symbol.asyncIterator, false);
There is nothing new in the async protocol. Same result object, same done, same value — only wrapped in a promise, so the consumer awaits each step instead of reading it. Everything you know about Symbol.iterator transfers, including that early exit calls return().
The fallback in the fifth and sixth assertions is the part that saves you writing adapters. for await looks for Symbol.asyncIterator, and if the object has only Symbol.iterator it uses that and awaits each value on the way out. So an array of promises works directly, which is the ordinary case for "fire off a few requests and handle them in order".
That convenience hides a cost worth naming. for await over an array of promises awaits them one at a time in order, so if the third resolves first you still wait for the first two. They were all started when the array was built, so this is not the serialisation problem of exercise 26 — but if you want results as they arrive rather than in order, you want Promise.all or a settled-as-they-come helper, not this loop.