Promise.race()
The Promise.race() method takes in an array of promises and takes the result of the promise that rejects or resolves the fastest. Like normal promises, the then() and catch() methods are used to retrieve the results of the fastest promise.
The Promise.race() method can be used to choose the quickest source when there are two similar sources of the same data.
Notice how the Promise.race() method is used to take the result of the faster promise:
let promise1 = new Promise((resolve,reject) => {
setTimeout(() => {
resolve("finished in two seconds");
},2000) //returns a resolved promise after 2 seconds
});
let promise2 = new Promise((resolve,reject) => {
setTimeout(() => {
resolve("finished in five seconds");
},5000) //returns a resolved promise after 5 seconds
});
Promise.race([promise1,promise2])
.then(result => {
console.log(result) // logs "finished in two seconds" because promise1 resolved first
}).catch(error => {
console.log(error)
});
The Promise.race() method can also be used to limit the amount of time promises have to resolve by including a promise that is forced to reject after a given amount of time.
Notice how the Promise.race() method is used to limit the amount of time a Promise has to resolve:
let promiseResolveTenSeconds = new Promise((resolve,reject) => {
setTimeout(() => {
resolve("finished in ten seconds");
},10000) //returns a resolved promise after 10 seconds
});
let promiseRejectFiveSeconds = new Promise((resolve,reject) => {
setTimeout(function(){
reject("error: promise took longer than 5 seconds to resolve");
},5000) //returns a rejected promise after 5 seconds
});
Promise.race([promiseResolveTenSeconds,promiseRejectFiveSeconds])
.then(result => {
console.log(result) // never occurs because promiseRejectFiveSeconds rejected
}).catch(error =>{
console.log(error) // logs "error: promise took longer than 5 seconds to resolve"
});