Promise(3.7) 自定义(手写)Promise —— 异步任务回调的执行

168 阅读1分钟

在状态改变时,调用then方法里面的回调 在then方法中判断pending状态做一些操作->保存回调函数,

增加callback属性:this.callack = {}

function Promise(executor){
    //resolve和reject都是函数
    
    //添加属性
    this.PromiseState = "pending";
    this.PromiseResult = null
    
    this.callack = {}
    
    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
        if(self.callback.onResolved){
            self.callback.onResolved(self.PromiseResult)
        }
        
    }
    
    //reject函数
    function reject(data){
       if(self.PromiseState !== 'pending') return
       //(1)修改对象的状态
        self.PromiseState = 'rejected'
        //(2)设置对象结果值
        self.PromiseResult = data
        if(self.callback.onRejected){
            self.callback.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.callack = {
           onResolved:onResolved,
           onRejected:onRejected
       }
    }
}