Promise(3.8) 自定义(手写)Promise —— 指定多个回调的实现

166 阅读1分钟

image.png

需要把上图中执行的回调都保存起来(多个then里面的回调)
方法:callack需要改成数组,
this.callacks = []
this.callacks.push({ onResolved:onResolved, onRejected:onRejected })

function Promise(executor){
    //resolve和reject都是函数
    
    //添加属性
    this.PromiseState = "pending";
    this.PromiseResult = null
    
    this.callacks = []
    
    const self = this;
    //resolve函数
    function resolve(data){
        if(self.PromiseState !== 'pending') return
        //(1)修改对象的状态
        //this.PromiseState //这里的this为window,因为resolve是直接调用的
        self.PromiseState = 'fulfilled'
        //(2)设置对象结果值
        self.PromiseResult = data
        self.callbacks.forEach(item => {
            item.onResolved(self.PromiseResult)
        })
        
    }
    
    //reject函数
    function reject(data){
       if(self.PromiseState !== 'pending') return
       //(1)修改对象的状态
        self.PromiseState = 'rejected'
        //(2)设置对象结果值
        self.PromiseResult = data
        if(self.callbacks.onRejected){
            self.callbacks.onRejected(self.PromiseResult)
        }
        self.callbacks.forEach(item => {
            item.onRejected(self.PromiseResult)
        })
    }
    
    //同步调用执行器函数
    try {
        executor(resolve,reject)
    }catch(e){
        reject(e)
    }
    
}

//添加then方法
Promise.prototype.then = function(onResolved,onRejected){
    if(this.PromiseState == 'fulfilled'){
        onResolved(this.PromiseResult)
    }
    if(this.PromiseState == 'rejected'){
        onRejected(this.PromiseResult)
    }
    
    //判断pending状态
    if(this.PromiseState == 'pending'){
       //保存回调函数,以便于在状态改变时,调用
       this.callacks.push({
           onResolved:onResolved,
           onRejected:onRejected
       })
    }
}