Skip to content

Instantly share code, notes, and snippets.

@kettanaito
Created August 18, 2023 09:53
Show Gist options
  • Save kettanaito/f67f55b1f2a4ea0ec2a2847ccb6b8d0e to your computer and use it in GitHub Desktop.
Save kettanaito/f67f55b1f2a4ea0ec2a2847ccb6b8d0e to your computer and use it in GitHub Desktop.
Yield Promise.race()
async function* yieldMany(promises) {
promises.forEach((p) => {
return p.then((value) => {
promises.splice(
promises.findIndex((xp) => xp === p),
1
);
return value;
});
});
while (promises.length > 0) {
yield await Promise.race(promises);
}
return "done";
}
const generator = yieldMany([
new Promise((r) => setTimeout(() => r(1), 200)),
new Promise((r) => r(2)),
new Promise((r) => setTimeout(() => r(3), 500)),
]);
async function run() {
console.log("result 1:", (await generator.next()).value);
console.log("result 2:", (await generator.next()).value);
console.log("result 3:", (await generator.next()).value);
console.log("result 4:", (await generator.next()).value);
}
run();
// result 1: 2
// result 2: 1
// result 3: 3
// result 4: done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment