The Promise.race
method allows developers to create a promise that resolves or rejects as soon as one of the promises in an iterable resolves or rejects. While widely supported in modern JavaScript environments, older browsers may lack native support for this method. In this Frontend interview article, we’ll explore how to create a polyfill for the Promise.race
method, ensuring compatibility across all browsers.
Understanding Promise.race:
The Promise.race
method takes an iterable of promises as input and returns a single promise that resolves or rejects as soon as one of the promises in the iterable resolves or rejects. It’s commonly used in scenarios where you want to implement a timeout for an asynchronous operation or race multiple asynchronous operations.
const promise1 = new Promise((resolve, reject) => {
resolve("Rowdy Coders");
});
const promise2 = new Promise((resolve, reject) => {
setTimeout(() => {
reject("Some Error")
}, 100);
});
const promise3 = 0;
const promiseArray = [promise1, promise2, promise3];
Here, Promise.
race takes an array of promises as an input that returns a single promise as below.
Promise.race(promiseArray).then(value => {
console.log(value);
});
// Output: "Rowdy Coders" (because promise1 resolves first)
Creating the Polyfill:
To create a polyfill for the Promise.race
method, we’ll check if the method is already defined. If not, we’ll define it and implement its functionality using a Promise constructor and a race condition. Here’s a simple implementation:
Promise.myRace = (arrayOfPromises) => {
return new Promise((resolve, reject) => {
for (let i = 0; i < arrayOfPromises.length; i++) {
Promise.resolve(arrayOfPromises[i])
.then((d) => resolve(d), (e) => reject(e))
}
});
};
Promise.myRace(promiseArray).then(value => {
console.log(value);
});
// Output: "Rowdy Coders" (because promise1 resolves first)
We will iterate over the promise array and we try to resolve or reject it.
Understanding the internals of Promise.race
and how to polyfill it expands our toolkit for handling asynchronous operations in JavaScript.
1 comment
[…] might ask to create a polyfill for this Promise.race method, This is one of the most asked interview […]