fe-interview icon indicating copy to clipboard operation
fe-interview copied to clipboard

手动实现一个promise.all

Open habc0807 opened this issue 4 years ago • 1 comments

https://juejin.im/post/6844904067798401038#comment

habc0807 avatar Sep 02 '20 08:09 habc0807

function  PromiseAll(promises) {
    return new Promise((resolve,reject) => {
        if(!Array.isArray(promises)){
            return reject(new TypeError('arguments muse be an array'))
        }

        const LEN = promises.length
        let counter = 0
        let result = new Array(LEN)

        for(let i = 0; i < LEN; i++){
            Promise.resolve(promises[i]).then((value) => {
                counter++;
                result[i] = value;

                if(counter === LEN){
                    return resolve(result)
                }
            }, (reason) => {
                return reject(reason)
            })
        }
   })
}


  // 测试
const pro1 = new Promise((res,rej) => {
    setTimeout(() => {
      res('1')
    },1000)
  })
  const pro2 = new Promise((res,rej) => {
    setTimeout(() => {
      res('2')
    },2000)
  })
  const pro3 = new Promise((res,rej) => {
    setTimeout(() => {
      res('3')
    },3000)
  })
  
  const proAll = PromiseAll([pro2, pro3, pro1])
  .then(res => 
   console.log(res) // 3秒之后打印 [ "2", "3", "1"]
  )
  .catch((e) => {
   console.log(e)
  })

habc0807 avatar Sep 03 '20 03:09 habc0807