Promise.race in JavaScript with Practical Examples
Promise.race Exercise:
Write a JavaScript program that demonstrates the use of Promise.race to return the first completed Promise.
Solution-1:
Code:
// Create three promises with varying delays
const promise1 = new Promise((resolve) => {
setTimeout(() => resolve('Promise 1 resolved!'), 3000); // Resolves after 3 seconds
});
const promise2 = new Promise((resolve) => {
setTimeout(() => resolve('Promise 2 resolved!'), 2000); // Resolves after 2 seconds
});
const promise3 = new Promise((resolve) => {
setTimeout(() => resolve('Promise 3 resolved!'), 1000); // Resolves after 1 second
});
// Use Promise.race to get the first resolved promise
Promise.race([promise1, promise2, promise3]).then((result) => {
console.log(result); // Output: Promise 3 resolved!
});
Output:
"Promise 3 resolved!"
Explanation:
- Three promises are created with different delays (1, 2, and 3 seconds).
- 'Promise.race' returns the result of the first promise that resolves, which is 'promise3' in this case.
- The resolved value of 'promise3' is logged to the console.
Solution-2:
Code:
// Create promises for simulating API calls with varying delays
const apiCall1 = new Promise((resolve, reject) => {
setTimeout(() => resolve('API Call 1 Success'), 1500); // Resolves after 1.5 seconds
});
const apiCall2 = new Promise((resolve, reject) => {
setTimeout(() => resolve('API Call 2 Success'), 1000); // Resolves after 1 second
});
const apiCall3 = new Promise((resolve, reject) => {
setTimeout(() => reject('API Call 3 Failed'), 2000); // Rejects after 2 seconds
});
// Use Promise.race to handle the first completed promise
Promise.race([apiCall1, apiCall2, apiCall3])
.then((result) => {
console.log(result); // Output: API Call 2 Success
})
.catch((error) => {
console.error(error); // Handles the rejection if it happens first
});
Output:
"API Call 2 Success"
Explanation:
- Three promises simulate API calls with different completion times (1, 1.5, and 2 seconds).
- 'Promise.race' resolves or rejects with the result of the first completed promise.
- In this case, 'apiCall2' resolves first, so its success message is logged.
- If a rejection happens first, the `catch` block handles it.
See the Pen promises-and-async-await-exercise-15 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus
Previous: Using Async/Await with Dynamic imports in JavaScript.
Next: Resolving Nested Promises in JavaScript with Async/Await.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics