2022-09-18笔试题00
请注意,本文编写于 532 天前,最后修改于 532 天前,其中某些信息可能已经过时。

面试高频手撕代码题

Promise 系列

实现 Promise.any()

const promiseAny = promises => {
  if (!Array.isArray(promises)) {
    throw new TypeError('Promises must be an array!');
  }
  if (promises.length === 0) return Promise.reject([]);

  return new Promise((resolve, reject) => {
    let count = 0;
    let errors = [];

    promises.forEach((promise, index) => {
      Promise.resolve(promise).then(
        value => {
          resolve(value);
        },
        err => {
          errors.push(err);
          count++;
          if (count === promises.length) {
            reject(new AggregateError(errors, 'All promises were rejected'));
            // AggregateError 请参考:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/AggregateError
          }
        }
      );
    });
  });
};

// test
const p1 = Promise.reject(123);
const p2 = Promise.resolve(456);
const p3 = new Promise((resolve, reject) => {
  setTimeout(reject, 100, 'lee');
});

promiseAny([]).then(res => {
  console.log(res); // Uncaught (in promise) []
});

promiseAny([p1, p2]).then(res => {
  console.log(res); // 456
});

promiseAny([p1, p3]).then(res => {
  console.log(res); // Uncaught (in promise) AggregateError: All promises were rejected
});

本文作者:前端小毛

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!