Skip to main content

Command Palette

Search for a command to run...

Understanding Promise.any() (with Custom Implementation)

Updated
2 min read
Understanding Promise.any() (with Custom Implementation)
S

I'm Shubham (@shubhamsinghbundela), I'm a Software Engineer, a Full-stack developer, a tech enthusiast, and a technical writer here on @Hashnode. I have a strong zeal to share my acquired knowledge and I am also willing to learn from others.

What is Promise.any()?

Promise.any() is used to run multiple promises in parallel and return the first successfully resolved promise.


Behavior:

  • If any one promise resolves, it immediately returns a resolved promise with that value.

  • If all promises reject, it returns a rejected promise with an AggregateError containing all errors.


Example

const p1 = Promise.reject("Error 1");
const p2 = Promise.resolve(20);
const p3 = Promise.resolve(30);

Promise.any([p1, p2, p3])
  .then(result => {
    console.log(result); // 20
  })
  .catch(err => {
    console.error(err);
  });

Rejection Case

const p1 = Promise.reject("Error 1");
const p2 = Promise.reject("Error 2");

Promise.any([p1, p2])
  .then(result => {
    console.log(result);
  })
  .catch(err => {
    console.error(err); 
    // AggregateError: All promises were rejected
    // err.errors => ["Error 1", "Error 2"]
  });

Key Concept

Promise.any() follows success-first behavior — one success is enough.


Custom Implementation of Promise.any()

Let’s now understand how Promise.any() works internally by implementing it ourselves.

Code :

function promiseAny(promises) {
    return new Promise((resolve, reject) => {
        let errors = [];
        let rejectedCount = 0;

        if (promises.length === 0) {
            reject(new Error("Empty iterable"));
        }

        promises.forEach((element, index) => {
            Promise.resolve(element)
                .then((data) => {
                    resolve(data); // first success wins
                })
                .catch((err) => {
                    errors[index] = err;
                    rejectedCount++;

                    if (rejectedCount === promises.length) {
                        reject(new AggregateError(errors, "All promises were rejected"));
                    }
                });
        });
    });
}

🔗Before You Go Further

If you haven’t read about Promise.all(), check it out here:

Understanding Promise.all (with Custom Implementation)
https://shubhamsinghbundela.hashnode.dev/understanding-promise-all-with-custom-implementation

More from this blog

Shubham Tech. Blog's

55 posts

Problem Solver | Currently Working As a Full Stack Developer, Community Leader At @Dev_Matrix | Previously Contributor at @RealDevSquad, @TeamShiksha