Skip to content

Instantly share code, notes, and snippets.

@bishil06
Last active March 1, 2021 09:36
Show Gist options
  • Save bishil06/97af1dded298c19fa11b37f98411da2e to your computer and use it in GitHub Desktop.
Save bishil06/97af1dded298c19fa11b37f98411da2e to your computer and use it in GitHub Desktop.
JavaScript Async Generator that yields in the order of the earliest completion of the promises
const util = require("util")
function delay(time, data) {
return new Promise((res, rej) => {
setTimeout(() => res(data), time);
})
}
async function *promiseMarathon(...promises) {
while (promises.length > 0) {
const finish = await Promise.race(promises).then(f => {
promises = promises.filter(p => util.inspect(p).includes("pending"));
return f;
});
yield finish;
}
}
async function test() {
for await(const p of promiseMarathon(delay(3000, [1, 2, 3]), delay(2000, [10, 20, 30]), delay(1000, [100, 200, 300]))) {
console.log(p);
}
}
/*
[ 100, 200, 300 ]
[ 10, 20, 30 ]
[ 1, 2, 3 ]
*/
// async function test() {
// for await(const p of promiseMarathon(delay(0, [1, 2, 3]), delay(0, [10, 20, 30]), delay(0, [100, 200, 300]))) {
// console.log(p);
// }
// }
// test();
/*
[ 1, 2, 3 ]
[ 10, 20, 30 ]
[ 100, 200, 300 ]
*/
// async function test() {
// for await(const p of promiseMarathon(delay(1000, [1, 2, 3]), delay(3000, [10, 20, 30]), delay(2000, [100, 200, 300]))) {
// console.log(p);
// }
// }
// test();
/*
[ 1, 2, 3 ]
[ 100, 200, 300 ]
[ 10, 20, 30 ]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment