๐Ÿš€ Implementing a Polyfill for Promise.any in JavaScript

๐Ÿš€ Implementing a Polyfill for Promise.any in JavaScript
Anmol KansalAnmol Kansalโ€ขFeb 28, 2025โ€ข2 min read

Promise.any is a useful method in JavaScript that takes an array of promises and resolves as soon as any one of them fulfills. If all promises reject, it returns an AggregateError.

Letโ€™s break down how we can implement our own polyfill for Promise.any! ๐Ÿ”ง

๐Ÿง Understanding Promise.any

โœ… Expected Behavior

  • It resolves with the first fulfilled promise.
  • If all promises reject, it rejects with an AggregateError.

๐Ÿ“Œ Example Usage

const p1 = Promise.reject('Error 1');
const p2 = new Promise((resolve) => setTimeout(() => resolve('Success!'), 1000));
const p3 = Promise.reject('Error 2');

Promise.any([p1, p2, p3]).then(console.log).catch(console.error);

Output:

"Success!" (after 1 second)

If all promises reject:

AggregateError: All promises were rejected

๐Ÿ› ๏ธ Implementing Promise.any Polyfill

Hereโ€™s how we can implement it:

function promiseAny(promises) {
    return new Promise((resolve, reject) => {
        let errors = [];
        let pending = promises.length;

        if (pending === 0) {
            return reject(new AggregateError([], 'All promises were rejected'));
        }

        promises.forEach((promise, index) => {
            Promise.resolve(promise)
                .then(resolve)
                .catch((error) => {
                    errors[index] = error;
                    pending--;
                    if (pending === 0) {
                        reject(new AggregateError(errors, 'All promises were rejected'));
                    }
                });
        });
    });
}

It uses Promise.resolve() to handle non-promise values. It resolves on the first success. It Collects errors and rejects only when all promises fail. It mimics the AggregateError behavior.

๐Ÿ“Œ Usage Example

const p1 = Promise.reject('Error 1');
const p2 = new Promise((resolve) => setTimeout(() => resolve('Success!'), 1000));
const p3 = Promise.reject('Error 2');

promiseAny([p1, p2, p3]).then(console.log).catch(console.error);

๐ŸŽ“ Final Thoughts

Implementing polyfills deepens our understanding of JavaScript's built-in functions. Promise.any is particularly useful when you only need the first successful resultโ€”common in API failover strategies or parallel task execution.

Let me know if you found this useful! ๐Ÿš€

Anmol Kansal

Anmol Kansal

Full Stack Developer

I have close to 5 years of industry experience building scalable web interfaces and robust frontend infrastructures. I specialize in React, TypeScript, Next.js, and full-stack JavaScript โ€” with a strong focus on clean code, performant bundle loading, and highly optimized animation layers.

More blogs