/*
* 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.status = 'resolve';
this.value = value;
this.fulfilledCallback && this.fulfilledCallback();
}
};
let reject = (reason)=>{
if(this.status =='pending'){
this.status = 'reject';
this.reason = reason;
this.rejectCallback && this.rejectCallback();
}
};
cback(resolve, reject);
}
Promise.prototype.then = function(resolve, reject){
let that = this;
if (that.status === "resolve") {
resolve(that.value);
}
if (that.status === "reject"){
reject(that.reason)
}
if(that.status == 'pending'){
that.fulfilledCallback = function(){
resolve(that.value)
}
that.rejectCallback = function(){
reject(that.reason)
}
}
}
测试
function test(){
return new Promise(function(resolve,reject){
setTimeout(function(){
resolve('2秒');
},)
})
}
test()
.then(function(msg){
console.log(msg);
})