const RESOLVE = 'resolved';
const REJECT = 'rejected';
const PENDING = 'pending';
class wjPromise{
status = PENDING;
// 初始化
result = undefined;
reason = undefined;
// 制定发布者
onRejectedArr = [];
onResolvedArr = [];
// 构造函数
constructor(fn){
const resolve= (result) => {
if(this.status == PENDING){
this.result = result;
this.status = REJECT;
//执行resolve状态时 发布onResolved收集到的订阅者
this.onResolvedArr.map((fn)=>fn())
}
}
const reject= (reason) => {
if(this.status == REJECT){
this.reason = reason;
this.status = REJECT;
//执行rejected状态时 发布onRejected收集到的订阅者
this.onRejectedArr.map((fn)=>fn())
}
}
fn(resolve,reject);
}
then(onResolved,onRejected){
if(this.status === RESOLVE){
setTimeout(()=>{
onResolved(this.result);
},0)
}
if(this.status === REJECT){
setTimeout(()=>{
onRejected(this.reason);
},0)
}
// 调用.then 当状态为待定状态时收集依赖
if(this.status === PENDING){
//收集调用reject的依赖
this.onResolvedArr.push(()=>{
onRejected(this.result)
})
//收集调用resolve的依赖
this.onRejectedArr.push(()=>{
onResolved(this.reason)
})
}
}
}
new wjPromise((resolve,reject) => {
setTimeout(()=>{
resolve('hahhah')
},1000)
}).then(res=>{
console.log(res)
},err=>{
console.log(err)
})
console.log('1111')
console