手写Promise.all与Promise.race方法

如有错误,请指出,毕竟写之前笔者也没看过标准写法,没有使用迭代器进行循环,读者可以自行尝试。

// custom Promise.all
Promise.myAll = function (args) {
  const length = args.length
  let resolveNum = 0
  const result = new Array(length)
  return new Promise((resolve, reject) => {
    try {
      if (!length) resolve(result)
      for (let i = 0; i < length; i++) {
        ;(function (i) {
          args[i].then((res) => {
            result[i] = res
            if (++resolveNum === length) {
              // console.log("promises finised")
              resolve(result)
            }
          })
        })(i)
      }
    } catch (error) {
      reject(error)
    }
  })
}

// custom Promise.race
Promise.myRace = function (args) {
  let resolved = false
  return new Promise((resolve, reject) => {
    try {
      args.forEach((p) => {
        p.then((res) => {
          if (!resolved) {
            resolved = true
            resolve(res)
          }
        })
      })
    } catch (error) {
      reject(error)
    }
  })
}

// for test

const args = [Promise.resolve(10), Promise.resolve(20), Promise.resolve(30)]

const all = Promise.all(args)
const myAll = Promise.myAll(args)

const race = Promise.race(args)
const myRace = Promise.race(args)

上一篇:角色创建


下一篇:Promise.all和Promise.race的理解和使用