Promise.race() polyfill
5-min frontend interview prep
Welcome to another episode of 5-min frontend interview prep , today we will see promise.race()
Promise.race() method will return a promise that fullfils or rejects as soon as one of promises in an iterable(array) fullfills or rejects .
What do we understand by the defination is
it will return a promise , the returned promise fulfills or rejects a any one of input promises fulfills or rejects and returned promise resolves with the value of input promise or rejects with reason of input promise
Let's stop talking and we will implement
const promiseRace = function (promiseArray) {
return new Promise((resolve, reject) => {
promiseArray.forEach((promise) => {
Promise.resolve(promise)
.then(resolve) // resolve with the value of the first resolved promise
.catch(reject); // reject with the reason of the first rejected promise
});
});
};
so try to remember this it will return a promise which will resolve or reject as soon as any one promise will resolve or reject , we use promise.race when we wanna which async task completes first