Skip to content

Instantly share code, notes, and snippets.

@bakkot
Last active January 26, 2023 03:08
Show Gist options
  • Save bakkot/a338838aee667517adb03edfa83aaed1 to your computer and use it in GitHub Desktop.
Save bakkot/a338838aee667517adb03edfa83aaed1 to your computer and use it in GitHub Desktop.
'use strict';
// please do not use this code in real life
let AsyncIteratorProto = (async function*(){})().__proto__.__proto__.__proto__;
AsyncIteratorProto.map =
function(fn) {
return {
__proto__: AsyncIteratorProto,
next: async () => {
let { done, value } = await this.next();
if (done) return { done: true };
return {
done: false,
value: await fn(value),
};
},
};
};
let sleep = ms => new Promise(res => setTimeout(res, ms));
async function* inner() {
yield 0;
console.log('starting first inner sleep');
await sleep(80);
console.log('finished first inner sleep, starting second inner sleep');
yield 1;
await sleep(10);
console.log('finished second inner sleep');
yield 2;
}
async function slowPrinter(v) {
console.log('starting slow print of', v);
await sleep(50);
console.log('finished slow print of', v);
}
let it = inner().map(slowPrinter);
it.next();
it.next();
it.next();
/*
This prints the following:
starting first inner sleep
starting slow print of 0
finished slow print of 0
finished first inner sleep, starting second inner sleep
starting slow print of 1
finished second inner sleep
starting slow print of 2
finished slow print of 1
finished slow print of 2
From the first two lines you can see that the inner generator can be working at the same time as the mapper
From the last two lines you can see that the mapper can be working at the same time as itself
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment