The Promise.race() method in JavaScript is used to handle multiple promises and return the result of the first resolved promise.
It returns a new promise that is settled as soon as any of the promises passed as an iterable argument to the method are settled, whether it is resolved or rejected. The resolved or rejected value of the returned promise will be the value of the first settled promise.
Syntax for Promise.race() method:
Promise.race(iterable);
Here, the iterable argument is an array or any other iterable object that contains one or more promises.
When to use Promise.race() method:
-
When you have multiple asynchronous operations to perform and you only need the result of the first one to complete.
-
When you want to perform multiple operations in parallel and want to take the fastest result.
Example:
Let’s say you have to make multiple requests to different APIs and you only need the response of the fastest API call.
Instead of waiting for all the requests to complete, you can use the Promise.race()
method to get the result of the first request that completes.
const fetch1 = fetch("https://api1.example.com");
const fetch2 = fetch("https://api2.example.com");
const fetch3 = fetch("https://api3.example.com");
Promise.race([fetch1, fetch2, fetch3])
.then((response) => console.log(response))
.catch((error) => console.log(error));
In the above example, the Promise.race() method takes an array of three promises, and it returns a new promise that resolves with the response of the fastest request. If the fastest request returns a response, the .then()
method is called and the response is logged to the console. If any of the requests fail, the .catch()
method is called and the error is logged to the console.
If you are using the Promise.race() method to handle multiple promises, it is important to note that the other unresolved promises are still running in the background. It only resolves or rejects with the first resolved or rejected value.
const promise1 = new Promise((resolve, reject) => {
setTimeout(resolve, 500, "first");
});
const promise2 = new Promise((resolve, reject) => {
setTimeout(resolve, 100, "second");
});
Promise.race([promise1, promise2]).then((value) => console.log(value));
// Output: 'second'
In the above example, the Promise.race()
method takes an array of two promises, and it returns a new promise that resolves with the value of the first promise that resolves. Here, the promise2
resolves faster than promise1
, so the .then()
method is called with the value 'second'
.
Promise.race() method can be used in many scenarios. For example, you can use it to implement a timeout for a promise. If a promise takes too long to resolve, you can use the Promise.race() method to return a rejection after a certain amount of time.
const promiseWithTimeout = (promise, timeout) => {
let timeoutID;
const timeoutPromise = new Promise((resolve, reject) => {
timeoutID = setTimeout(() => {
reject(new Error(`Promise timed out after ${timeout} ms`));
}, timeout);
});
return Promise.race([promise, timeoutPromise]).finally(() =>
clearTimeout(timeoutID)
);
};
const myPromise = new Promise((resolve, reject) => {
setTimeout(resolve, 1000, "success");
});
promiseWithTimeout(myPromise, 500)
.then((value) => console.log(value))
.catch((error) => console.log(error.message));
// Output: Error: Promise timed out after 500 ms
In the above example, the promiseWithTimeout()
function takes two arguments, the first one is the promise and the second one is the timeout duration in milliseconds. The function returns a new promise that either resolves with the result of the original promise or rejects with an error message if the promise takes too long to resolve.
The Promise.race() method is used to race the original promise and a timeout promise that is created inside the promiseWithTimeout() function. If the original promise resolves before the timeout promise, the .then() method is called with the resolved value. If the timeout promise resolves before the original promise, the .catch() method is called with an error message.
The clearTimeout() function is used in the finally block to clear the timeout if the original promise resolves or rejects before the timeout duration.
Promise.race() method in JavaScript is a useful tool for handling multiple promises and returning the result of the first resolved promise. It is particularly useful when you want to perform multiple asynchronous operations in parallel and take the fastest result.
You can use it to race promises against each other, implement a timeout for a promise, or fetch data from multiple APIs.
Thank you for reading, and let’s have conversation with each other
Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.