šŸ† FrontendGeek Leaderboard is live !! Signin & Check your position on the leaderboard

Blog/NotesConcept

Promise.allSettled Polyfill in JavaScript - Step by Step Explanation

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.

Expert

Frontendgeek

Last Updated Mar 27, 2025


Advertisement

 

Table of content:

  1. Understand Promise.allSettled Static Method
  2. Promise.allSettled Polyfill in JavaScript - Step by Step Explanation
  3. Handle Multiple Aync API Calls using Promise.allSettled

Understand Promise.allSettled Static Method

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: "<>"}

Example

// 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' }
]

Promise.allSettled Polyfill in JavaScript - Step by Step Explanation

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.allSettled Polyfill Implementation Code:

Promise.customAllSettled = function(promises) {
    return Promise.all(
      promises.map(promise =>
        Promise.resolve(promise)
          .then(value => ({ status: 'fulfilled', value }))
          .catch(reason => ({ status: 'rejected', reason }))
      )
    );
};

Example of Handling Multiple Aync API calls using Promise.allSettled

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'}

šŸ“£Final Note:

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

ā©Topics to Learn Next

  1. Notes to Master Promise Methods in JavaScript: all(), allSettled(), race() and any()
  2. Promise Polyfill in JavaScript - Step by Step Explanation 
  3. Promise.all Polyfill in JavaScript - Detailed Explanation [For Interviews]

 


Share this post now:

Advertisement

šŸ’¬ Comments (0)

Login to comment

Advertisement

Flaunt You Expertise/Knowledge & Help your Peers

Sharing your knowledge will strengthen your expertise on topic. Consider writing a quick Blog/Notes to help frontend folks to ace Frontend Interviews.

Advertisement


Other Related Blogs

Understanding popstate event in Single Page Applications (SPAs)

Vijay Sai Krishna vsuri

Last Updated Aug 21, 2025

A Quick guide about popstate event in JavaScript, If you’ve ever hit the back button in your browser and wondered how your Single-Page Application knows which view to render, this guide is for you.

Master Hoisting in JavaScript with 5 Examples

Alok Kumar Giri

Last Updated Jun 2, 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.

setTimeout Polyfill in JavaScript - Detailed Explanation

Anuj Sharma

Last Updated Aug 3, 2025

Explore the implementation of setTimeout in JavaScript with a detailed explanation for every step. Understand all scenarios expected to implement the setTimeout polyfill.

Best Cheat Sheet for Frontend Machine Coding Interview Round

Anuj Sharma

Last Updated Jun 13, 2025

A comprehensive cheat sheet for the Frontend Machine Coding Interview Round, which helps to revise all the important machine coding & UI design concepts before the interview.

20+ Frontend Machine Coding Interview Questions (JS + React)

Anuj Sharma

Last Updated Jun 27, 2025

A detailed list of 20+ most asked Frontend Machine Coding Interview Questions and resources both in JavaScript & React. Also covers expected functional/Non-functional requirements in this Interview.

JavaScript Essentials: Call, Apply and Bind Methods Explained with Polyfills

Kirtesh Bansal

Last Updated Aug 31, 2025

A beginner-friendly guide to understanding call, apply, and bind methods in JavaScript, along with step-by-step call, apply and bind polyfill implementations that are often asked in interviews.

FrontendGeek
FrontendGeek

Ā© 2024 FrontendGeek. All rights reserved