Promise(3.4) 自定义(手写)Promise —— throw抛出异常改变状态

249 阅读1分钟
function Promise(executor){
    //resolve和reject都是函数
    
    //添加属性
    this.PromiseState = "pending";
    this.PromiseResult = null
    
    const self = this;
    //resolve函数
    function resolve(data){
        //(1)修改对象的状态
        //this.PromiseState //这里的this为window,因为resolve是直接调用的
        self.PromiseState = 'fulfilled'
        //(2)设置对象结果值
        self.PromiseResult = data
    }
    
    //reject函数
    function reject(data){
       //(1)修改对象的状态
        self.PromiseState = 'rejected'
        //(2)设置对象结果值
        self.PromiseResult = data
    }
    
    //同步调用执行器函数
    try {
        executor(resolve,reject)
    }catch(e){
        reject(e)
    }
    
}

//添加then方法
Promise.prototype.then = function(onResolved,onRejected){

}