Skip to content

Promise.all

https://www.douyin.com/video/7438179107776564490

js
Promise.myAll = function (promises) {
  let res, rej
  const p = new Promise((resolve, reject) => {
    res = resolve
    rej = reject
  })
  let i = 0
  const result = []
  for (const item of promises) {
    const index = i
    i++
    Promise.resolve(item).then((data) => {
      result[index] = data
      i-- // 注意这里不会造成循环死锁(i 混乱),因为这是异步的,当执行到这一行时,循环早已结束了
      if (i === 0) {
        res(result)
      }
    }, rej)
  }
  if (i === 0) {
    res([])
  }
  return p
}

基于 MIT 许可发布