When the whole world is about to rain, let's make it clear in our heart together

热爱前端开发,专注于前端

手动编写一个promise.all函数

Promise.all = function(iterable) {
  return new Promise((resolve, reject) => {
    let result = []
    for(const item of iterable) {
      item.then(data => {
        result.push(data)
      }, reason=> {
        result = reason
        return
      })
    }

    resolve(result)
  })
}

//下面是测试用例
let p1 = new Promise((resolve, reject) => {
  resolve(666)
})

let p2 = new Promise((resolve, reject) => {
  resolve(888)
})

let p3 = new Promise((resolve, reject) => {
  resolve(999)
})

let p6 = new Promise((resolve, reject) => {
  reject(222)
})

let p4 = Promise.all([p1, p2, p3])

p4.then(data => {
  console.log(data)
})
//[666, 888, 999]
let p7 = Promise.all([p1, p3, p6])

p7.then(data => {
  console.log(data)
})
//222

 

posted @ 2022-02-12 15:40  婷风  阅读(49)  评论(0编辑  收藏  举报