js 手写 Promise

/*
 * pending:初始化成功
 * fulfilled:成功
 * rejected:失败
 * */
function Promise(cback){
    this.status = 'pending';
    this.value = undefined
    this.reason = undefined
    this.fulfilledCallback = undefined;
    this.rejectCallback = undefined;
    
    let resolve = (value)=>{
        if(this.status=='pending' && this.fulfilledCallback){
            this.status = 'resolve';
            this.value = value;
            this.fulfilledCallback();
        }
    };
    let reject = (reason)=>{
        if(this.status =='pending' && this.rejectCallback){
            this.status = 'reject';
            this.reason = reason;
            this.rejectCallback();
        }
    };
    cback(resolve, reject);
}
Promise.prototype.then = function(resolve, reject){
    if (this.status === "resolve") {
        resolve(this.value);
    }
    if (this.status === "reject"){
        reject(this.reason);
    }
    let that = this;
    if(this.status == 'pending'){
        this.fulfilledCallback = function(){
                resolve(that.value)
        }
        this.rejectCallback = function(){
                reject(that.reason)
        }
    }
}

测试

function test(){
    return new Promise(function(resolve,reject){
            setTimeout(function(){
                resolve('2秒');
            },2000)
        })
}
test()
.then(function(msg){
    console.log(msg);
})

猜你喜欢

转载自www.cnblogs.com/bruce-gou/p/10782940.html