Deep dive into Promise.allSettled Polyfill in JavaScript, which helps to understand the internal implementation of Promise.allSettled method to handle parallel calls with failure cases.
Frontendgeek
Last Updated Mar 27, 2025
Advertisement
Table of content:
Static Promise.allSettled([Promises]) function works similar to Promise.all() method to execute all the promises parallelly but rather than returning a failure response in case of one or more rejected promises, allSettled method takes array of promises as an input, and returns a promise as a response which got fulfilled when all the promises got settled (either fulfilled or rejected).
The fulfilled response contains an array of object which includes the results for all the input promises. All the fulfilled responses contains the status as "fulfilled" and the resolved value for example {status: "fulfilled", value: "<>"}
, and all the rejected response contains status as "rejected" along with the "reason" key which included the rejected reason example {status: "rejected", reason: "<>"}
// Promise.allSettled Example
// Creating three promises
const promise1 = Promise.resolve('First promise fulfilled');
const promise2 = Promise.resolve('Second promise fulfilled');
const promise3 = Promise.reject('Third promise rejected');
// Using Promise.allSettled to handle all promises, regardless of whether they are fulfilled or rejected
Promise.allSettled([promise1, promise2, promise3])
.then(results => {
console.log(results);
});
Output
[
{ status: 'fulfilled', value: 'First promise fulfilled' },
{ status: 'fulfilled', value: 'Second promise fulfilled' },
{ status: 'rejected', reason: 'Third promise rejected' }
]
Step 1: Promise.allSettled() returns a promise, so as part of the first step we need to retuned a promise but since allSettled also need to process all the promises parallelly we need to use the Promise.all() method internally for parallel execution of promises.
Step 2: As part of the second step, all the input promises needs to be iterated using a map (because it returns an processed array, which will going to be the input for Promise.all method).
Step 3: In the next step we just need to resolve the each promise, passed in each iteration of map. If the promise got fulfilled it adds {status: "fulfilled", value: "<v>"} to the array other wise in case of rejected promise, it will go to a catch block which adds rejected object {status: "rejected", reason: "<reason>"}
Promise.customAllSettled = function(promises) {
return Promise.all(
promises.map(promise =>
Promise.resolve(promise)
.then(value => ({ status: 'fulfilled', value }))
.catch(reason => ({ status: 'rejected', reason }))
)
);
};
One of the most common case of using Promise.allSettled is to execute parallel API calls, where successful execution of all the API call is not mandatory. allSettled() method provides a convenient way to handle fulfilled and rejected API calls, so that application can retry the failed api calls again.
// Example: Multiple DOG API calls handled using Promise.allSettled()
// Helper function to fetch a random dog image from the Dog API
function fetchDogImage(urlPath) {
return fetch(`https://dog.ceo/api/breeds/image/${urlPath}`)
.then(response => {
if (!response.ok) {
throw new Error('Failed to fetch dog image');
}
return response.json();
})
}
// Simulating multiple Dog API calls, with some failures
const apiCalls = [
fetchDogImage('random'), // Successful call
fetchDogImage('random'), // Successful call
fetchDogImage('random'), // Successful call
fetchDogImage('failed'), // Simulate a failure here by causing an error in the URL (incorrect API endpoint)
fetchDogImage('random') // Successful call
];
// Use Promise.allSettled to handle all API calls
Promise.allSettled(apiCalls)
.then(results => {
results.forEach((result, index) => {
if (result.status === 'fulfilled') {
console.log(`API call ${index + 1}: Success! Dog image URL`, result.value);
} else {
console.log(`API call ${index + 1}: Failed. Reason:`, result.reason);
}
});
})
.catch(error => {
console.error('Unexpected error occurred:', error);
});
š»Checkout the Live Code here - JS Bin
Output
API call 1: Success! Dog image URL {message: 'https://images.dog.ceo/breeds/briard/n02105251_12.jpg', status: 'success'}
API call 2: Success! Dog image URL {message: 'https://images.dog.ceo/breeds/akita/512px-Akita_inu.jpg', status: 'success'}
API call 3: Success! Dog image URL {message: 'https://images.dog.ceo/breeds/bulldog-english/jager-2.jpg', status: 'success'}
API call 4: Failed. Reason: Error: Failed to fetch dog image
API call 5: Success! Dog image URL {message: 'https://images.dog.ceo/breeds/african/n02116738_4734.jpg', status: 'success'}
Promise.allSettled() static method provides a powerful way to call the promises parallelly which results as a response of all the settled promises whether those are fulfilled or rejected. This helps in the partial execution of the promises, and particularly helpful where out of many promises one of the promise got rejected due to some reason.
This is the preferred way to call APIs when the APIs are independent and failure of an API doesn't effect the other API calls
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