Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

实现promise.all和promise.race #132

Open
wlin00 opened this issue Apr 27, 2021 · 0 comments
Open

实现promise.all和promise.race #132

wlin00 opened this issue Apr 27, 2021 · 0 comments
Labels
ECMAScript ECMAScript

Comments

@wlin00
Copy link
Collaborator

wlin00 commented Apr 27, 2021

1、Promise.all的实现

promise.all方法:
当有一个promise出错时,则reject其错误;或者当所有promise都resolve后统一返回一个结果数组

const selfPromiseAll = (promises) => {
  return new Promise((resolve, reject) => {
    const resArr = []
    let index = 0
    const deal = (idx, res) => {
      index++
      resArr[idx] = res
      if (index === promises.length) {
        resolve(resArr)
      }
    }
    for (let i = 0; i < promises.length; i++) {
      Promise.resolve(promises[i]).then((res) => {
        deal(i, res)
      }, (err) => {
        return reject(err)
      })
    }
  })
}

2、Promise.race

返回最快执行的结果,不论状态是resolve或reject

const selfPromiseRace = (promises) => {
  return new Promise((resolve, reject) => {
    for (let i = 0; i < promises.length; i++) {
      Promise.resolve(promises[i]).then((value) => {
        return resolve(value)
      }, (err) => {
        return reject(err)
      })
    }
  })
}
@wlin00 wlin00 added the ECMAScript ECMAScript label Apr 27, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
ECMAScript ECMAScript
Projects
None yet
Development

No branches or pull requests

1 participant