实现简单的Promise
2018-06-01 本文已影响0人
TRYao
class Promise{
constructor(executor){
// 默认是等待状态
this.status = 'pending';
this.value = undefined;
this.reason = undefined;
// 存放成功回调函数
this.onResolveCallbacks = [];
this.onRejectedCallbacks = [];
let resolve = (data) => {
// this指的是实例
if(this.status === 'pending'){
this.value = data;
this.status = 'resolved';
this.onResolveCallbacks.forEach(fn=>fn());
}
}
let reject = (reason) => {
// this指的是实例
if(this.status === 'pending'){
this.value = reason;
this.status = 'rejected';
this.onRejectedCallbacks.forEach(fn=>fn());
}
}
// 执行时可能发生异常
try{
executor(resolve,reject);
}catch(e){
reject(e);
}
}
then(onFulfilled,onRejected){
if(this.status === 'resolve'){
onFulfilled(this.value);
}
if(this.status === 'reject'){
onRejected(this.value);
}
if(this.status === 'pending'){
this.onReslovedCallbacks.push(()=>{
onFulfilled(this.value);
})
this.onRejectedCallbacks.push(()=>{
onRejected(this.reason);
})
}
}
}