class MyPrimise {
constructor(fn) {
this.status = 'pendding';
this.thenList = [];
this.catchList = [];
const resolveAync = ()=>{
setTimeout(this.resolve.bind(this),0);
//将resolve放到异步队列执行 [标准实现为微任务队列,此demo为宏任务队列]
}
const rejectAsync = ()=>{
setTimeout(this.reject.bind(this),0);
}
typeof fn === 'function' && fn( resolveAync,rejectAsync);
}
resolve(res) {
if (this.status !== 'pendding') return; //已经resolve/reject的实例不再处理
this.status = 'resolved'
this.thenList.forEach(f=>f())
}
reject(err) {
if (this.status !== 'pendding') return;
this.status = 'rejected'
this.catchList.forEach(f=>f())
}
then(cb) {
this.thenList.push(cb);
return this;
}
catch(cb) {
this.catchList.push(cb);
return this;
}
}
let pro = new MyPromise(
(res, rej) => {
console.log(1);
res();
console.log(2)
});
pro.then(() => { console.log(3) }).then(()=>{ console.log(5) })
console.log(4);
输出结果:1 2 4 5 3