Promise规范以及手写Promise

1.Promise的规范

在这里插入图片描述
用这个规范来举一个例子:

var promise1 = new Promise((resolve,reject)=>{reject()})

promise1 
.then(null,function(){
  return 123 
})
.then(null,null)  
.then(
  ()=>{
    console.log('promise2 已完成')
  },
 ()=>{
    console.log('promise2 已拒绝')

第一眼看结果会返回什么呢??

1.首先promise1返回一个已拒绝状态,然后会进入.then的回调,只要这个地方不throw err,都会进入promise的onfulfilled,记住这个已完成状态和promise1没关系了

2.根据我上面提到的规范,只要onFulffilled或者onRejected返回一个值X,就会进入onFulffilled状态,所以123成功返回

3.到.then(null.null)这一步之后,再看第三条规则,onFulffilled不是函数并且状态是已完成,必须成功执行并返回相同的值,所以123再次成功返回

4.所以最后会打印结果’promise2 已完成’

5.123也可以获取到

 .then(
	 (value)=>{
     console.log('promise2 已完成',value)   //value为123
 },

2.手写Promise

class Promise{
  constructor(handleFunction){
      this.status = 'pending'
      this.value = undefined
      this.fulfilledList = []
      this.rejectedList = []
      
      handleFunction(this.triggerResolve.bind(this),this.triggerReject.bind(this))
  }

  triggerResolve(val){
      //当前的promise状态已经变成了resolve,要执行后续的操作
      setTimeout(()=>{
        if(this.status !== 'pending') return

        if(val instanceof Promise){
           val.then(
             value => {},
             err => {}
           )
        }else{
          //resolve方法传入的是普通值
          this.status = 'fulfilled'
          this.value = val
          this.triggerFulfilled(val)
        }
      },0)
  }

  triggerFulfilled(val){
     this.fulfilledList.forEach(item =>item(val))
     this.fulfilledList = []
  }

  triggerReject(){
      
  }

  then(onFulfilled,onRejected){
    const { value , status } =  this;
    return new Promise((onNextFulfilled,onNextRejected)=>{
      function onFinalFulfilled(val){
        if(typeof onFulfilled !== 'function'){
          onNextFulfilled(val)
        }else{
          const res = onFulfilled(val)
          if(res instanceof Promise){
            res.then(onNextFulfilled,onNextRejected)
          }else{
            onNextFulfilled(res)
          }
        }
      }
      function onFinalRejected(error){
        if(typeof onRejected !== 'function'){
          onNextRejected(error)
        }else{
          let res = null
          try{
            res = onRejected(error)
          } catch(e){
            onNextRejected(e)
          }
          if(res instanceof Promise){
            res.then(onNextFulfilled,onNextRejected)
          }else{
            onFulfilled(res)
          }
        }
      }
        switch(status){
          case 'pending':{
            this.fulfilledList.push(onFinalFulfilled)
            this.rejectedList.push(onFinalRejected)
            break;
          }
          case 'fulfilled':{
            onFinalFulfilled(value)
            break;
          }
        }
    })
  }
  catch(onRejected){
    return this.then(null,onRejected)
  }

  static resolve(value){
     if(value instanceof Promise)  return value
     return new Promise(resolve => resolve(value))
  }

  static reject(){

  }

  static all(list){
     return new Promise((resolve,reject)=>{
       let count = 0 ;
       const values = []
       for(const [i,promiseInstance] of list.entries()){
         Promise.resolve(promiseInstance)
         .then(res=>{
           values[i] = res;
           count++
           if(count === list.length){
             resolve(values)
           }
         },err =>{
           reject(err)
         })
       }
     })
  }

  static race(list){
     return  new Promise((resolve,reject)=>{
       list.forEach(item=>{
         Promise.resolve(item).then(res=>{
           resolve(res)
         },err =>{
           reject(err)
         })
       })
     })
  }
}

如何使用呢?

首先最简单的用法就是

const promise = new Promise(function(resolve,reject){
  resolve('lsh')
})

多个then调用

const promise = new Promise(function(resolve,reject){
  resolve('lsh')
})
promise
.then(function(str){console.log(str); return str })
.then(function(str2){console.log('resolve2',str2)})

all调用

const promise = function(time){
  return new Promise(function(resolve,reject){
    return setTimeout(resolve,time)
  })
}

Promise.all([promise(1000),promise(2000)])
.then(function(){
  console.log('all promise resolved')
})

then延时调用

const promiseInstance = promise(0)
setTimeout(function(){
  promiseInstance.then(function(){console.log('你好啊');})
},3000)

其他功能暂未开发…

猜你喜欢

转载自blog.csdn.net/weixin_45389051/article/details/109465517