ES2021 introduced any and race methods to the Promise class.

The promise resolves to the following states

  • pending is the initial value not fulfilled or rejected
  • fulfilled - settled with a successful result
  • rejected- rejected with an error result

ES2020 introduced [Promise.all](/settled /javascript/es11-promise-allsettled) that is used to run multiple promises parallelly and return the result when all promises are either fulfilled or rejected.

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

Race method allows returning the response.

  • when one of the promises is settled successfully, that means these promises can either be rejected or fulfilled.

Promise.any example

let’s create two promise object 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 promises is resolved or rejected.

Promise.race example

In this example, One of the promises is rejected and race is resolved to be rejected with an 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