-
-
Save bakkot/a338838aee667517adb03edfa83aaed1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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