Promise 基础

262 阅读1分钟
function Promise(task){
    let status = 'pending';
    // let fullCalls = [];
    // let resjectCalls = [];
    let that = this;
    that.fullCalls = [];
    that.resjectCalls = [];
    this.status = status;
    function reslove(value){
        if(that.status=='pending'){
            that.status='resloved';
            that.fullCalls.forEach(item => {
                item(value)
            });
        }
    }
    function resject(value){
        if(that.status=='pending'){
            that.status='resjected';
            that.resjectCalls.forEach(item => {
                item(value)
            });
        }
    }
    task(reslove,resject);
}
Promise.prototype.then = function(fullCall,resjectCall){
    let that = this;
    that.fullCalls.push(fullCall);
    that.resjectCalls.push(resjectCall);
}

let p1 = new Promise(function(reslove,resject){
    setTimeout(function(){
        return reslove('成功1')
    },500);
    setTimeout(function(){
        return resject('失败1')
    },400);
})
p1.then(function(value){
    console.log(value)
},function(value){
    console.log(value)
})

let p2 = new Promise(function(reslove,resject){
    setTimeout(function(){
        return reslove('成功2')
    },500);
    setTimeout(function(){
        return resject('失败2')
    },600);
})
p2.then(function(value){
    console.log(value)
},function(value){
    console.log(value)
})

结果: 失败1 成功2