Skip to content

实现 Promise.all 方法 #45

Description

@Inchill
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]
})

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions