ES2021 introduced any and race methods to Promise class.

Promise is always resolved to following states

  • pending is initial value not fullfilled or rejected
  • fullfilled - settled with successful result
  • rejected- rejected with an error result ES2020 introduced [Promise.all](/settled /javascript/es11-promise-allsettled) that is used to run multiple promises parallely and return the result when all promises are either fulfilled or rejected.

SO any method in promise also applied to array of promises. When one of promise is successfully fulfilled, and all other promises in an array are fullfilled as rejected.

Race method allows to return the response

  • when one of the promise is succesfully settle, that means these promise can either rejected or fullfilled.

Promise.any example

let’s create a two promise which resolves in 1 and 2 seconds

const promise1 = new Promise((resolve, reject) => {
    setTimeout(() => resolve("one done"), 1000);

});
const promise2 = new Promise((resolve, reject) => {
    setTimeout(() => resolve("two done"), 2000);

});

And the result is all promise are resolved

(async function () {
  const promiseStatus = await Promise.any([promise1, promise2]);
  console.log(promiseStatus); // Prints "one done", "two done"
})();

AggregateError error is thrown if none of the promise is resolved or rejected.

Promise.race example

In this example, One of the promise is reject and race is resolved to rejected with error.

const promise1 = new Promise((resolve, reject) => {
    setTimeout(() => reject("failed"), 1000m new Error('Fail'));

});
const promise2 = new Promise((resolve, reject) => {
    setTimeout(() => resolve("two done"), 2000);

});

Promise.race returns

Promise.race([promise1, promise2]).then(
    value => {
        console.log(`fullfilled`);
    },
    reason => {
        console.log(`rejected`);
    }
);

output

rejected