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 Sep 18, 2025


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
  6. Promise.any polyfill in JavaScript explained

Share this post now:

💬 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.

Polyfill for map, filter, and reduce in JavaScript

Anuj Sharma

Last Updated Oct 2, 2025

Explore Polyfill for map, filter and reduce array methods in JavaScript. A detailed explanation of Map, filter and reduce polyfills in JS helps you to know the internal working of these array methods.

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.

Implement Infinite Currying Multiplication in JavaScript: mul(2)(3)(4)

Anuj Sharma

Last Updated Oct 13, 2025

Understand the step-by-step implementation of Infinite Currying Multiplication in JavaScript with a code example.

How does JWT (JSON Web Token) Authentication work - Pros & Cons

Frontendgeek

Last Updated Sep 25, 2025

Understand the JWT(JSON Web Token) and how JWT decode works. It also covers how the end-to-end JWT authentication works between client & server, along with the pros and cons of using JWT.

Stay Updated

Subscribe to FrontendGeek Hub for the frontend interview preparation, interview experiences, curated resources and roadmaps.

FrontendGeek
FrontendGeek

© 2024 FrontendGeek. All rights reserved