手写一个promise

97 阅读1分钟

一个简单的手写promise

class Promise2 {
  queue1 = [] // queue1 为了容纳成功之后的函数们
  queue2 = [] // queue2 为了容纳失败之后的函数们
  constructor(fn){ // new Promise2(fn),构造函数
    const resolve = (data)=>{ // fn 接受 resolve 并在成功的时候调用
      setTimeout(()=>{ // 要等一会,否则 queue1 和 queue2 为空
        for(let i =0;i<this.queue1.length;i++){//遍历queue1
          this.queue1[i](data)//执行queue1里面的函数
        }
      })
    }
    const reject = (reason)=>{//fn 接受一个reject并在失败的时候调用
      setTimeout(()=>{
      for(let i =0;i<this.queue2.length;i++){
          this.queue2[i](reason)//执行then里面传进来的失败函数
        }
      })
    }
    
    fn(resolve, reject)
  }
  then(s, e){
    this.queue1.push(s)
    this.queue2.push(e)
    return this
  }
}
p1 = new Promise2((resolve, reject)=>{
  console.log('hi2'); 
  if(Math.random()>0.5){
    resolve('大')
  }else{
    reject('小')
  }
})
p1.then((data)=>{console.log('成功')},  (reason)=>{console.log('失败')})
.then(()=>{console.log('成功2')},  ()=>{console.log('失败2')})
.then(()=>{console.log('成功3')},  ()=>{console.log('失败3')})
// 失败承包制

会先打出来hi2,这个时候因为延时执行了rejectresolve,等到一会的时候,then已经将失败要执行的函数还有成功要执行的函数分别放到了数组里面,这时候再执行reject或者resolve时就会打出"失败"

image.png