Skip to content

Instantly share code, notes, and snippets.

@jfet97
Last active June 8, 2019 11:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jfet97/d117524e6353244999b4a7a8bf21e95b to your computer and use it in GitHub Desktop.
Save jfet97/d117524e6353244999b4a7a8bf21e95b to your computer and use it in GitHub Desktop.
racePromisePool
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
}
})();
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;
}
}
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