Promise.any() Polyfill

Promise.any() takes an iterable of Promise objects. It returns a single promise that fulfills as soon as any of the promises in the iterable fulfills, with the value of the fulfilled promise. If no promises in the iterable fulfill (if all of the given promises are rejected), then the returned promise is rejected with an AggregateError, a new subclass of Error that groups together individual errors.

Promise.anyPolyfill = (promises) => {
  const promiseErrors = [];
  let counter = 0;

  return new Promise((resolve, reject) => {
    promises.forEach((promise, promiseIndex) => {
      promise
        .then((val) => resolve(val))
        .catch((error) => {
          promiseErrors[counter] = error;
          counter++;
          if (counter === promises.length) {
            reject(promiseErrors);
          }
        });
    });
  });
};

Example

const test1 = new Promise((resolve, reject) => {
  setTimeout(reject, 500, "one");
});
const test2 = new Promise((resolve, reject) => {
  setTimeout(reject, 600, "two");
});
const test3 = new Promise((resolve, reject) => {
  setTimeout(reject, 700, "three");
});

Promise.anyPolyfill = (promises) => {
  const promiseErrors = [];
  let counter = 0;

  return new Promise((resolve, reject) => {
    promises.forEach((promise, promiseIndex) => {
      promise
        .then((val) => resolve(val))
        .catch((error) => {
          promiseErrors[counter] = error;
          counter++;
          if (counter === promises.length) {
            reject(promiseErrors);
          }
        });
    });
  });
};

Promise.anyPolyfill([test1, test2, test3])
  .then((value) => {
    console.log(value);
  })
  .catch((err) => {
    console.log(err);
  });