Promise.any implementation

Promise.any() - MDN

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

Simple polyfill

Promise.any = values => new Promise((resolve, reject) => {  
  const length = values.length
  const errors = []
  let resolved = false

  values.map(item => (
    Promise.resolve(item).then(v => {
      if (!resolved) {
        resolved = true
        resolve(v)
      }
    }).catch(e => {
      errors.push(e)
      if (errors.length === length) {
        reject(new AggregateError(errors, 'No Promise in Promise.any was resolved'))
      }
    })
  ))
})

Test

const pErr = new Promise((resolve, reject) => {  
  reject("总是失败");
});

const pSlow = new Promise((resolve, reject) => {  
  setTimeout(resolve, 500, "最终完成");
});

const pFast = new Promise((resolve, reject) => {  
  setTimeout(resolve, 100, "很快完成");
});

Promise.any([pErr, pSlow, pFast]).then((value) => {  
  console.log(value);
  // pFast fulfils first
})
// 很快完成

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

Promise.any([ppp]).catch((err) => {  
  console.log(err);
})
// VM691:6 AggregateError: No Promise in Promise.any was resolved
//    at <anonymous>:16:18
正在加载 Disqus 评论组件...