高级前端
js
【Q490】如何实现一个 promise.any

如何实现一个 promise.any

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

Author 回答者: hwb2017 (opens in a new tab)

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));
          }
        },
      );
    });
  });
};

Author 回答者: cloudGrin (opens in a new tab)

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));
          }
        },
      );
    });
  });
};

错误的顺序应该按照promise的顺序返回