Last active
June 8, 2019 11:28
-
-
Save jfet97/d117524e6353244999b4a7a8bf21e95b to your computer and use it in GitHub Desktop.
racePromisePool
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
const delay = ms => new Promise(ok => setTimeout(() => ok(ms), ms)); | |
;(async () => { | |
const pool = [ | |
delay(2000), | |
delay(1000), | |
delay(3000), | |
delay(500), | |
]; | |
for await (const res of racePromisePool(pool)) { | |
// use `res` here | |
} | |
})(); |
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
async function *racePromisePool([...prs] = []) { | |
while(prs.length > 0) { | |
let { val, idx }= await Promise.race(prs.map((p, idx) => p.then(val => ({ val, idx })))); | |
prs.splice(idx, 1); | |
yield val; | |
} | |
} |
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
async function* racePromisePool(prs = []) { | |
if (prs.length == 0) return; | |
let { val, idx } = await Promise.race(prs.map((p, idx) => p.then(val => ({ val, idx })))); | |
yield val; | |
yield* racePromisePool(prs.filter((p, i) => i !== idx)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment