Promise(3.9) 自定义(手写)Promise —— 同步修改状态then方法结果返回

471 阅读1分钟

image.png

image.png promise.then()返回的新promise的结果状态由什么决定?
(1)简单表达:由then()指定的回调函数执行的结果决定(下图中的result)
(2)详细表达:
①如果抛出异常,新promise变为rejected,reason为抛出的异常
②如果返回的是非promise的任意值,新promise变为resolved,value为返回的值
③如果返回的是另一个新promise,此promise的结果就会成为新promise的结果

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){
    return new Promise((resolve,reject) => {
        if(this.PromiseState == 'fulfilled'){
           try{
                //onResolved(this.PromiseResult)
                let result = onResolved(this.PromiseResult)
                //判断result是否为一个promise对象
                if(result instanceod Promise){
                    //如果是 Promise类型的对象
                    result.then(v => {
                        resolve(v)
                    })
                }else{
                    //结果的对象状态为成功
                    resolve(result)
                }
           }catch(e){
               reject(e)
           }
        }
        if(this.PromiseState == 'rejected'){
            onRejected(this.PromiseResult)
        }

        //判断pending状态
        if(this.PromiseState == 'pending'){
           //保存回调函数,以便于在状态改变时,调用
           this.callacks.push({
               onResolved:onResolved,
               onRejected:onRejected
           })
        }
    })
}