spaasteam / spaas-daily-practice

spaas团队的每日一练,欢迎小伙伴们提交踊跃答案!
4 stars 2 forks source link

第 45 题: 设计并实现Promise. race() #52

Open Jack-rainbow opened 5 years ago

Jack-rainbow commented 5 years ago

设计并实现Promise. race()

Htongbing commented 5 years ago
Promise.myRace = function(promises) {
  return new Promise((resolve, reject) => {
    for (let item of promises) {
      Promise.resolve(item).then(resolve).catch(reject)
    }
  })
}
cjfff commented 5 years ago
const sleep = time => new Promise((resolve) => setTimeout(() => resolve(time), time))

Promise.$race = function(promiseList) {
  return new Promise((resolve, reject) => {
    promiseList.forEach((p) => {
      Promise.resolve(p).then(resolve).catch(reject)
    })
  })
}

Promise.$race([sleep(3000), sleep(2000), sleep(2500)]).then((res) => {
   console.log(res); // 2000
})
Jack-rainbow commented 5 years ago
Promise.race = (promises = []) => {
    return new Promise((resolve, reject) => {
        promises.forEach(v=>{
            Promise.resolve(v).then(resolve).catch(reject)
        })
    })
}