fe-notes icon indicating copy to clipboard operation
fe-notes copied to clipboard

实现 Promise.all 方法

Open Inchill opened this issue 3 years ago • 0 comments

function promiseAll (arr = []) {
  return new Promise((resolve, reject) => {
    let ans = []
    let count = 0

    arr.forEach((item, index) => {
      Promise.resolve(item).then(res => {
        ans[index] = res // index 块级作用域确保结果数组顺序和原数组一致,也可以在 for 循环里使用 let
        count++ // 统计 resolve 个数

        if (count === arr.length) {
          resolve(ans)
        }
      }).catch(e => reject(e))
    })
  })
}

function task1 () {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(1)
    }, 2000)
  })
}

function task2 () {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(2)
    }, 100)
  })
}

let arr = [task1(), task2()]
promiseAll(arr).then(res => {
  console.log('ans ===', res) // 输出 [1, 2]
})

Inchill avatar Sep 27 '22 12:09 Inchill