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

Blog/NotesConcept

Promise.any Polyfill in JavaScript - Detailed Explanation

A step-by-step detailed explanation of Promise.any polyfill in JavaScript to understand the internal implementation to handle race conditions among promises to result in a single resolved promise.

beginner

Frontendgeek

Last Updated Apr 2, 2025


Advertisement

Jump to the topic

  1. How does Promise.any work in javascript?
  2. Promise.any Polyfill in Javascript - Detailed Explanation

How does Promise.any work in JavaScript?

Promise.any() takes multiple promises and returned the first one that resolved. If all promises reject, it returns an AggregateError object containing all the error messages for all the rejected promises. Promise.any static method is quite useful in the cases where in the application we are just looking for the first success response and sequence doesn't matter in this case.

Real life Use Cases:

If your app serves images from multiple CDNs, you want the fastest CDN to load the image first.

In WebRTC-based applications, connect to the fastest signaling server for real-time communication.

Examples

1. When any one of the promise got fulfilled

const p1 = new Promise((resolve, reject) => setTimeout(reject, 1000, "Error from p1"));
const p2 = new Promise((resolve, reject) => setTimeout(resolve, 2000, "Success from p2"));
const p3 = new Promise((resolve, reject) => setTimeout(resolve, 3000, "Success from p3"));

Promise.any([p1, p2, p3])
  .then((result) => console.log("First fulfilled promise:", result))
  .catch((error) => console.error("All promises rejected:", error));

Output

// After 2 seconds
First fulfilled: Success from p2

Explanation:

  • p1 rejects after 1s.

  • p2 resolves after 2s, this is the first fulfilled promise that's why Promise.any() returns its value.

  • p3 resolves after 3s, but since p2 promise already fulfilled, p3 is ignored.

2. When all the promises got rejected

When all the promises reject, Promise.any() throws an AggregateErrorAggregateError is an object which contains all the rejected responses as part of an errors array.

const p1 = Promise.reject("Error from p1");
const p2 = Promise.reject("Error from p2");
const p3 = Promise.reject("Error from p3");

Promise.any([p1, p2, p3])
  .then((result) => console.log("First fulfilled:", result))
  .catch((error) => {
       console.log(error instanceof AggregateError); // true
       console.error("All promises rejected:", error.errors);
  });

output:

true 
All promises rejected: [ 'Error from p1', 'Error from p2', 'Error from p3' ]

Expected Functionality for Promise.any Implementation

Here are the Promise.any expected functionalities that needs to be take care while implementing polyfill for Promise.any() .

❌ - Not executed, βœ… - Executed

Case1: Promise.any should return the first resolved value

Promise.any([
  Promise.reject("Error A"),
  Promise.resolve("Success B"), // First resolved promise
  Promise.resolve("Success C"),
])
  .then(result => console.log("βœ… First resolved:", result))
  .catch(error => console.error("❌ Unexpected error:", error));

// Output
βœ… First resolved: Success B

Returns the first resolved promise, others got ignored.

Promise.any([
  new Promise(res => setTimeout(res, 500, "Success A")), // resolved first
  new Promise((res, rej) => setTimeout(rej, 300, "Error B")),
  new Promise(res => setTimeout(res, 600, "Success C")), // resolved second
])
  .then(result => console.log("βœ… First resolved:", result))
  .catch(error => console.error("❌ Unexpected error:", error));

// Output
βœ… First resolved: Success A

 

Case2: When all promise rejected or passed iterable is empty, Promise.any should throw AggregateError

Promise.any([
  Promise.reject("Error A"),
  Promise.reject("Error B"),
])
  .then(result => console.log("❌ Success:", result))
  .catch(error => console.log("βœ… AggregateError caught:", error.errors));

// Output
βœ… AggregateError caught: ["Error A", "Error B"]

Empty iterable

Promise.any([])
  .then(result => console.log("❌ Unexpected success:", result))
  .catch(error => console.log("βœ… AggregateError caught:", error.errors));

// Output
βœ… AggregateError caught: []

 

Case3: In case of already resolved promise it directly returns that first resolved promise

Promise.any([
  Promise.resolve("Immediate Success1"),
  Promise.resolve("Immediate Success2"),
  Promise.reject("Immediate Reject")
])
  .then(result => console.log("βœ… Immediate resolved:", result))
  .catch(error => console.error("❌ Unexpected error:", error));

// Output
βœ… Immediate resolved: Immediate Success1

 

Case4: In case of non-promise iterable, Promise.any() returns the non-promise values if that is the first one to process, before any resolved promise

//--------Example 1--------------
Promise.any([
  Promise.reject("Error"),
  Promise.resolve("world"),
  "Non-promise"
])
  .then(result => console.log("βœ… First resolved:", result))
  .catch(error => console.error("❌ Unexpected error:", error));

//Output
βœ… First resolved: world

//--------Example 2--------------
Promise.any([
  "Non-promise",
  Promise.reject("Error"),
  Promise.resolve("world")
])
  .then(result => console.log("βœ… First resolved:", result))
  .catch(error => console.error("❌ Unexpected error:", error));

//Output
βœ… First resolved: Non-promise

Promise.any Polyfill in Javascript - Detailed Explanation

Here are the 3 steps with explanation, those are required to implement the polyfill of Promise.any()

Step 1: Handle empty iterable input

If Promise.any([]) is called, it immediately rejects with AggregateError.

if (!Array.isArray(promises) || promises.length === 0) {
  reject(new AggregateError([], "All promises were rejected"));
  return;
}

Step 2: Loop over all the input promises

Maintain an array of rejections to track the all rejection messages those will pass to AggregatorError, along with the length of the input promises.

let rejections = [];
let pending = promises.length;

promises.forEach((promise, index) => {
     // Loop over
})

Step 3: Pass each promise to Promise.resolve()

In the loop pass each promise to Promise.resolve(), and track the fulfilled and rejected promises. In case of resolved promise, first resolved promise will be returned, other wise in case of rejected promises push the rejected error message for AggregatorError and keep track of the length of the promises. If all the promises found as rejected then an AggregatorError object should be returned with all the rejected error messages with rejections array.

Promise.resolve(promise)
  .then(resolve)
  .catch((err) => {
    rejections[index] = err;
    pending--;

    if (pending === 0) {
      reject(new AggregateError(rejections, "All promises were rejected"));
    }
  });

Full Promise.any Polyfill Implementation Code

Promise.customAny = function (promises) {
    return new Promise((resolve, reject) => {
      // Step 1
      if (!Array.isArray(promises) || promises.length === 0) {
        reject(new AggregateError([], "All promises were rejected"));
        return;
      }
      
      // Step 2
      let rejections = [];
      let pending = promises.length;

      promises.forEach((promise, index) => {
        // Step 3
        Promise.resolve(promise)
          .then(resolve) // βœ… First fulfilled promise resolves
          .catch((err) => {
            rejections[index] = err;
            pending--;

            // ❌ If all promises are rejected, return AggregateError
            if (pending === 0) {
              reject(new AggregateError(rejections, "All promises were rejected"));
            }
          });
      });
    });
  };

// Test
Promise.customAny([
  new Promise(res => setTimeout(res, 500, "Success A")), // resolved first
  new Promise((res, rej) => setTimeout(rej, 300, "Error B")),
  new Promise(res => setTimeout(res, 600, "Success C")), // resolved second
])
  .then(result => console.log("βœ… First resolved:", result))
  .catch(error => console.error("❌ Unexpected error:", error));

// Output
βœ… First resolved: Success A

⏩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]
  4. Promise.allSettled Polyfill in JavaScript - Step by Step Explanation
  5. Promise.race Polyfill in Javascript - Detailed Explanation

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

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.

Understanding Critical Rendering Path (CRP) to Improve Web Performance

Anuj Sharma

Last Updated Aug 3, 2025

Understand what all steps are involved in the Critical Rendering Path (CRP) and how optimization of different steps can improve the overall web-vitals of a web application

clearTimeout polyfill in JavaScript - Detailed Explanation

Anuj Sharma

Last Updated Aug 3, 2025

Understand the implementation of the clearTimeout polyfill in JavaScript with a detailed explanation of each and every step.

FrontendGeek
FrontendGeek

Β© 2024 FrontendGeek. All rights reserved