Promise(3.3) 自定义(手写)Promise —— resolve与reject代码实现

222 阅读1分钟

resolve函数执行完成之后
(1)promise的状态会从pending变为fulfilled
(2)修改对象结果值

reject函数执行完成之后
(1)promise的状态从pending变为rejected
(2) 修改对象的结果值

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
    }
    
    //同步调用执行器函数
    executor(resolve,reject) 
}

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

}