JS简单实现Promis(没有实现then链调用)
function _Promise(fn){
if(typeof fn !== 'function') {
throw new TypeError('_Promise resolver undefined is not a function')
}
this.state = 'pending';
this.result = undefined;
this.eventPool = {
A: function(){},
B: function(){}
}
var that = this;
function resolve(res){
change('resolved', res)
}
function reject(rej){
change('rejected', rej)
}
function change(state, result){
if(that.state !== 'pending') return;
that.state = state;
that.result = result;
setTimeout(function(){
that.state === 'resolved'? that.eventPool.A(that.result): that.eventPool.B(result);
})
}
try{
fn(resolve, reject);
}catch(err){
change('rejected', err);
}
}
_Promise.prototype.then = function(A, B){
this.eventPool.A = A;
this.eventPool.B = B;
}
_Promise.resolve = function(res) {
return new _Promise(function(resolve){
resolve(res)
});
};
_Promise.reject = function(res) {
return new _Promise(function(undefined, rejecte){
rejecte(res)
});
};
let p = new _Promise(function(resolve, reject){
reject(300);
});
p.then(res=>{
console.log(res);
}, rej=>{
console.log(rej);
});
_Promise.resolve(200).then(res=>{
console.log(res)
});
_Promise.reject(400).then(res=>{}, rej=>{
console.log('失败', rej)
});
console.log('同步');