`
// 手写一个promise
class Promise2 {
static stat = 'pending'; // pending|filled|rejected 有三种状态
static onResolvedCallbacks = []; // 成功之后遍历then中成功的所有回调函数
static onRejectedCallbacks = [];// 存储then中失败的回调函数
constructor(fun = ()=>{}) {
fun(Promise2.resolve,Promise2.reject)
}
static resolve(conent){ // 成功的回调
Promise2.stat = 'filled';
// 成功之后遍历then中失败的所有回调函数
Promise2.onResolvedCallbacks.reduce((now,next)=>{
return next(now)
},conent)
}
static reject(conent){ // 失败 回调
Promise2.stat = 'rejected';
// 失败之后遍历then中失败的所有回调函数
Promise2.onRejectedCallbacks.reduce((now,next)=>{
return next(now)
},conent);
}
then(fun = ()=>{}){ // 正常回调
Promise2.onResolvedCallbacks.push(fun);
return this;
}
catch(fun = ()=>{}){ // 错误捕获方法
Promise2.onRejectedCallbacks.push(fun);
return this;
}
finally(fun = ()=>{}){
Promise2.onResolvedCallbacks.push(fun);
Promise2.onRejectedCallbacks.push(fun);
}
}
let callPromise2 = new Promise2((resolve,reject)=>{
setTimeout(()=>{
const num = 111;
reject(num)
},2000)
})
callPromise2.then((res)=>{
console.log(res)
return 222
}).then((res)=>{
console.log(res)
return 333
}).catch((error)=>{
console.log(error)
}).finally((end)=>{
console.log(end)
})
// Promise.resolve(111).then((res)=>{
// console.log(res)
// })
// Promise2.resolve(111).then((res)=>{
// console.log(res)
// })