极客时间返利平台,你可以在上边通过山月的链接购买课程,并添加我的微信 (shanyue94) 领取返现。

# 如何实现一个 promise.any

Issue

欢迎在 Gtihub Issue 中回答此问题: Issue 499 (opens new window)

Author

回答者: hwb2017 (opens new window)

Promise.any 的行为跟 Promise.all 刚好相反

Promise.any = (promiseArray) => {
  return new Promise((resolve, reject) => {
    const _promiseArray = Array.from(promiseArray);
    const length = _promiseArray.length;
    const rejectedArray = [];
    _promiseArray.forEach((item) => {
      Promise.resolve(item).then(
        (val) => {
          resolve(val);
        },
        (reason) => {
          rejectedArray.push(reason);
          if (rejectedArray.length === length) {
            reject(new AggregateError(rejectedArray));
          }
        }
      );
    });
  });
};
Last Updated: 11/27/2021, 6:11:48 PM