const PENDING = 'PENDING';
const RESOLVED = 'RESOLVED';
const REJECTED = 'REJECTED'
class Promise{
constructor(executor){
this.status = PENDING;// 默认为等待状态
this.value = undefined; //成功的原因
this.reason = undefined; // 失败的原因
this.resolvedCallbacks = [];// 存放成功的回调函数
this.rejectedCallbacks = [];// 存放失败的回调函数
let resolve = (value) => {
this.value = value;
this.status = RESOLVED;
this.resolvedCallbacks.forEach((method)=>{
method(this.value);
})
}
let reject = (reason) => {
this.reason = reason;
this.status = REJECTED;
this.rejectedCallbacks.forEach((method)=>{
method(this.reason);
})
}
try{
executor(resolve,resolve)
}catch(e){
console.log(e)
}
}
then(onfulfilled,onrejected){
if( this.status === RESOLVED){
onfulfilled(this.value);
}
if( this.status === REJECTED){
onrejected(this.reason);
}
if( this.status === PENDING){ // 通过发布订阅的方式支持异步
this.resolvedCallbacks.push(()=>{
onfulfilled(this.value);
})
this.rejectedCallbacks.push(()=>{
onrejected(this.reason);
})
}
}
}
var psy = new Promise(function(resolve,reject){
setTimeout(()=>{
resolve('kkkk')
},1000)
})
psy.then((msg)=>{
console.log(msg, 'msg');
},(msg)=>{
console.log(msg, 'msg');
})
</script>;
promise简单的封装
最新推荐文章于 2024-05-23 11:18:33 发布