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

如何实现一个 promise.any

Issue 欢迎在 Gtihub Issue 中回答此问题: Issue 499

Author 回答者: hwb2017

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

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的顺序返回