The Promise.race() method returns a promise that fulfills or rejects as soon as one of the promises in an iterable fulfills or rejects, with the value or reason from that promise.
Taken from MDN site.
I have 5 promises and I need to know once any 2 promises are resolved, taking performance under consideration.
const sleep = ms =>
new Promise(r => setTimeout(r, ms))
async function swimmer (name) {
const start = Date.now()
console.log(`${name} started the race`)
await sleep(Math.random() * 5000)
console.log(`${name} finished the race`)
return { name, delta: Date.now() - start }
}
const swimmers =
[ swimmer("Alice"), swimmer("Bob"), swimmer("Claire"), swimmer("David"), swimmer("Ed") ];
Promise.race(swimmers)
.then(({ name }) => console.log(`*** ${name} is the winner!!! ***`))
.catch(console.error)
This will return the fastest swimmer but I would like to print once I get 2 promises resolved.
How can I do it?
You could write a custom implementation of Promise.race that returns a promise that is resolved with the result of 2 promises that are resolved before others.
Following code example shows an implementation:
function customPromiseRace(promiseArr, expectedCount) {
return new Promise((resolve, reject) => {
if (promiseArr.length < expectedCount) {
throw new Error(`Not enough promises to get ${expectedCount} results`);
}
// array to store the results of fulfilled promises
const results = [];
for (const p of promiseArr) {
Promise.resolve(p).then(result => {
// push the promise fulfillment value to the "results"
// array only if we aren't already finished
if (results.length < expectedCount) {
results.push(result);
if (results.length === expectedCount) {
resolve(results);
}
}
}, reject);
}
});
}
const sleep = ms => new Promise(r => setTimeout(r, ms));
async function swimmer(name) {
const start = Date.now();
console.log(`${name} started the race`);
await sleep(Math.random() * 5000);
console.log(`${name} finished the race`);
return { name, delta: Date.now() - start };
}
const swimmers = [
swimmer('Alice'),
swimmer('Bob'),
swimmer('Claire'),
swimmer('David'),
swimmer('Ed'),
];
function customPromiseRace(promiseArr, expectedCount) {
return new Promise((resolve, reject) => {
if (promiseArr.length < expectedCount) {
throw new Error(`Not enough promises to get ${expectedCount} results`);
}
const results = [];
for (const p of promiseArr) {
Promise.resolve(p).then(result => {
if (results.length < expectedCount) {
results.push(result);
if (results.length === expectedCount) {
resolve(results);
}
}
}, reject);
}
});
}
customPromiseRace(swimmers, 2).then(console.log).catch(console.error);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With