class Promise{
constructor(excutorCallBack){
this.status='pending';
this.value = undefined;
this.fulfilledAry = [];
this.rejectedAry=[];
let resolveFn=(result)=>{
let timer = setTimeout(()=>{
clearTimeout(timer);
if(this.status !="pending")return;
this.status = 'fulfilled';
this.value = result;
this.fulfilledAry.forEach(item=>item(this.value));
},0);
}
let rejectFn = (reason)=>{
let timer= setTimeout(()=>{
clearTimeout(timer);
if(this.status !='pending')return;
this.status = 'rejected';
this.value = reason;
this.rejectedAry.forEach(item=>item(this.value));
},0);
}
excutorCallBack(resolveFn,rejectFn);
};
then(fulfilledCallBack,rejectedCallBack){
this.fulfilledAry.push(fulfilledCallBack);
this.rejectedAry.push(rejectedCallBack);
}
};
module.exports = Promise;
将此文件保存为promise1.js
test.js中调用进行测试:
let promise = require('./promise1');
new Promise((resolve,reject)=>{
setTimeout(()=>{
let t= Math.random();
console.log(t);
t <0.5?resolve(100):reject(-100);
},1000);
}).then(result=>{
console.log(result);
},(reason)=>{
console.log(reason);
});
console.log(3);