Promise 有三种状态:Pending 初始态; Fulfilled 成功态; Rejected 失败态
Promise是一种异步解决方案,
只能有以下两种方式,不可逆,不可以取消,
状态变化两个形式:
第一种:Pending -> Fulfilled
第一种:Pending -> Rejected
function Promise(executor) {
let self = this;
self.status = ‘pending‘; //等待态
self.value = undefined; //成功的返回值
self.reason = undefined; //失败的原因
function resolve(value){
if(self.status === ‘pending‘){
self.status = ‘resolved‘;
self.value = value;
}
}
function reject(reason) {
if(self.status === ‘pending‘) {
self.status = ‘rejected‘;
self.reason = reason;
}
}
try{
executor(resolve, reject);
}catch(e){
reject(e);// 捕获时发生异常,就直接失败
}
}
//onFufiled 成功的回调
//onRejected 失败的回调
Promise.prototype.then = function (onFufiled, onRejected) {
let self = this;
if(self.status === ‘resolved‘){
onFufiled(self.value);
}
if(self.status === ‘rejected‘){
onRejected(self.reason);
}
}
module.exports = Promise;