Implement a custom Promise.race() method
You are required to implement a custom Promise.race()
function.
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.
Solution
- Handle Non-Promises: We use
Promise.resolve(promise)
to ensure we're working with actual promises. This ensures the function works even if non-promises are passed in the array - Attach Callbacks: We use
then
andcatch
methods on the resolved promise to attach theresolve
andreject
callbacks of the outer promise. This ensures the outer promise settles based on the first settled inner promise (either fulfilled or rejected).
Code
This is a custom implementation of Promise.race
It resolves or rejects with the first settled promise (either resolved or rejected)
function promiseRace(promises) {
// Check if promises is an iterable
if (!Array.isArray(promises) && !promises[Symbol.iterator]) {
throw new TypeError('Argument must be an iterable of Promises');
}
return new Promise((resolve, reject) => {
for (const promise of promises) {
promise.then(resolve).catch(reject);
}
});
}
const promise1 = new Promise((resolve, reject) => {
setTimeout(resolve, 1000, 'slow promise');
});
const promise2 = new Promise((resolve, reject) => {
setTimeout(resolve, 500, 'fast promise');
});
promiseRace([promise1, promise2])
.then(value => console.log(value)) // Output: "fast promise"
.catch(error => console.error(error));
Summary
- A custom implementation of
Promise.race
can be created by manually iterating over the provided promises and resolving or rejecting as soon as the first one settles. - Ensure you have checked a non promises values.