Detailed step-by-step explanation of Promise.race polyfill in javascript to understand its internal working and handling of race conditions among promises.
Anuj Sharma
Last Updated Mar 27, 2025
Advertisement
Table of Content
Promise.race takes the iterable (such as array) of promises, and returns the first settled promise, here settled promise can be resolved or rejected. As name "race" suggested, whichever promise settled first will be returned by Promise.race() method.
Example 1: First settled promise: Rejected
In the below example the P3 promise rejected in the minimum time 50ms, that's why it get rejected before the other 2 promises and race will return the first settled (either resolved or rejected) promise.
// First settled promise - rejected
const p1 = new Promise((resolve) => setTimeout(() => resolve("P1 resolved"), 100));
const p2 = new Promise((resolve) => setTimeout(() => resolve("P2 resolved"), 200));
const p3 = new Promise((resolve, reject) => setTimeout(() => reject("P3 rejected"), 50));
Promise.race([p1, p2, p3])
.then((value) => console.log(`Fulfilled: ${value}`))
.catch((error) => console.log(`Error: ${error}`));
// Output
"Error: P3 rejected"
Example 2: First settled promise - Resolved
In the below example the P1 promise resolves in the minimum time 100ms, that's why it resolves before the other 2 promises and race will return the first settled (either resolved or rejected) promise.
// First settled promise - Resolved
const p1 = new Promise((resolve) => setTimeout(() => resolve("P1 resolved"), 100));
const p2 = new Promise((resolve) => setTimeout(() => resolve("P2 resolved"), 200));
const p3 = new Promise((resolve, reject) => setTimeout(() => reject("P3 rejected"), 150));
Promise.race([p1, p2, p3])
.then((value) => console.log(`Fulfilled: ${value}`))
.catch((error) => console.log(`Error: ${error}`));
// Output
"Fulfilled: P1 resolved"
Before understanding the custom implementation of Promise.race(), its important to understand the scenarios which Promise.race() needs to fulfill
// Promise resolved fist
const p1 = new Promise((resolve) => setTimeout(() => resolve("P1 resolved"), 50));
const p2 = new Promise((resolve) => setTimeout(() => resolve("P2 resolved"), 100));
Promise.race([p1, p2]).then(console.log); // Output: "P1 resolved"
// Promise rejected first
const p3 = new Promise((resolve, reject) => setTimeout(() => resolve("P3 rejected"), 50));
const p4 = new Promise((resolve) => setTimeout(() => resolve("P4 resolved"), 100));
Promise.race([p3, p4]).then(console.log); // Output: "P3 rejected"
If iterable contains any non-promise values (example - 45, 'Apple'), then these non-promise values should resolved immediately.
const p1 = new Promise((resolve) => setTimeout(() => resolve("P1 resolved"), 50));
Promise.race([42, p1]).then(console.log); // Output: 42
In case, if immediate rejecting promise (Promise.reject) passed It will caught first by Promise.race()
const p1 = new Promise((resolve) => setTimeout(() => resolve("P1 resolved"), 50));
const pImmediateReject = Promise.reject("Immediate rejection");
Promise.race([p1, pImmediateReject]).catch(console.log);
// Output: "Immediate rejection"
const p2 = new Promise((resolve, reject) => setTimeout(() => reject("P2 reject"), 50));
Promise.race([pImmediateReject, p2]).catch(console.log);
// Output: "Immediate rejection"
If an input is not iterable, it should throw a TypeError
.
Promise.race(45)
.then((value) => console.log(value))
.catch((error) => console.log(error));
// TypeError: number 45 is not iterable (cannot read property Symbol(Symbol.iterator))
In case of Empty array, the return promise from Promise.race() will never settled.
Promise.race([])
.then((value) => console.log(value))
.catch((error) => console.log(error));
// Output: Returned promise never settled to return any value or error
Step 1: Create a custom function which takes an iterable of promises.
Step 2: It returns a new Promise
that resolves or rejects as soon as one of the promises in the iterable settles (resolves or rejects).
Step 3: In this step, Loop over the iterable of Promises, and wrapped each promise in Promise.resolve()
to handle non-promise values.
First settled promise's result is used to settle the returned promise.
function customRace(promises) {
return new Promise((resolve, reject) => {
if (!Array.isArray(promises)) {
return reject(new TypeError("Argument must be an iterable"));
}
for (const promise of promises) {
Promise.resolve(promise).then(resolve, reject);
}
});
}
Advertisement
Advertisement
Advertisement
Alok Kumar Giri
Last Updated Apr 28, 2025
Code snippet examples which will help to grasp the concept of Hoisting in JavaScript, with solutions to understand how it works behind the scene.
Anuj Sharma
Last Updated Jan 9, 2025
Go through different ways to display dates using javascript date object. It covers examples of date object usage to understand the main concepts of javascript date object.
Anuj Sharma
Last Updated Jan 29, 2025
Understand the difference between HTTP/2 vs HTTP/1.1 based on the various parameters, which helps to understand the improvement areas of HTTP/2 over HTTP 1.1
Anuj Sharma
Last Updated Dec 10, 2024
A brief explanation of Cross-Origin Resource Sharing (CORS) concept to enable client application accessing resources from cross domain and HTTP headers involved to enable resource access.
Anuj Sharma
Last Updated Jan 16, 2025
Deep dive into promise.all polyfill in javascript will help to understand the working of parallel promise calls using Promise.all and its implementation to handle parallel async API calls.
Anuj Sharma
Last Updated Jan 9, 2025
Learn the best & quickest way to format phone number in JavaScript with or without country codes. This will help websites to show the phone numbers in a more human-readable format.
© 2024 FrontendGeek. All rights reserved