手撕Promise.any

Promise.any() 接收一个Promise可迭代对象,只要其中的一个 promise 成功,就返回那个已经成功的 promise 。如果可迭代对象中没有一个 promise 成功(即所有的 promises 都失败/拒绝),就返回一个失败的 promise AggregateError类型的实例,它是 Error 的一个子类,用于把单一的错误集合在一起。本质上,这个方法和Promise.all()是相反的。

Promise.any = function (promises) {
  return new Promise((resolve, reject) => {
    const length = promises.length;
    let rejectCount = 0;
    promises.forEach((promise) => {
      Promise.resolve(promise).then(value => {
        resolve(value)
      }, () => {
        rejectCount++
        if (rejectCount === length) {
          reject('AggregateError:All promises were rejected')
        }
      })
    })
  })
}


const pErr1 = new Promise((resolve, reject) => {
  reject('总是失败1');
});

const pErr2 = new Promise((resolve, reject) => {
  reject('总是失败2');
});

Promise.any([pErr1, pErr2]).catch((err) => {
  console.log(err);
})


const pErr3 = new Promise((_, reject) => {
  reject("总是失败3");
});

const pErr4 = new Promise((_, reject) => {
  reject("总是失败4");
});

const pSlow1 = new Promise((resolve, _) => {
  setTimeout(resolve, 600, "第二个完成");
});

const pSlow2 = new Promise((resolve, _) => {
  setTimeout(resolve, 500, "第一个完成");
});

const pFast = new Promise((resolve, _) => {
  setTimeout(resolve, 1000, "最后完成");
});

Promise.any([pErr3, pErr4, pSlow2, pSlow1, pFast]).then((value) => {
  console.log(value);
})

 

posted @ 2020-12-16 10:57  zt123123  阅读(161)  评论(0编辑  收藏  举报