const PENDING = 'pending';
const FULFILLED = 'fulfilled';
const REJECTED = 'rejected';
class MyPromise {
// 内部属性
#state = PENDING;
#result = undefined;
#handlers = [];
constructor(executor) {
const resolve = (data) => {
this.#changeState(FULFILLED, data)
};
const reject = (reason) => {
this.#changeState(REJECTED, reason)
};
//只能捕获同步的错误
try{
executor(resolve, reject)
}catch(err){
reject(err);
}
}
//改变状态,返回结果
#changeState(state, result) {
//promise只要开始运行,状态就只能有一个,不是完成就是失败
if (this.#state !== PENDING) return;
this.#state = state;
this.#result = result;
this.#run();
}
// 内部执行方法
#run(){
if(this.#state===PENDING) return;
while(this.#handlers.length){
const {onFulfilled,onRejected,resolve,reject} = this.#handlers.shift();
if(this.#state === FULFILLED){
if(typeof onFulfilled === 'function'){
onFulfilled(this.#result)
}
}else{
if(typeof onRejected === 'function'){
onRejected(this.#result)
}
}
}
}
//promise的then方法
then(onFulfilled,onRejected){
return new Promise((resolve,reject)=>{
this.#handlers.push({
onFulfilled,
onRejected,
resolve,
reject
})
this.#run();
})
}
}
const p = new MyPromise((resolve, reject) => {
setTimeout(()=>{
reject(1)
},3000)
});
p.then((res)=>{
console.log('promise 完成1',res)
},(err)=>{
console.log('promise 失败1',err)
})
p.then((res)=>{
console.log('promise 完成2',res)
})
p.then((res)=>{
console.log('promise 完成3',res)
},(err)=>{
console.log('promise 失败3',err)
})
p.then((res)=>{
console.log('promise 完成4',res)
},(err)=>{
console.log('promise 失败4',err)
})
console.log(p)
09-25
3464
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
12-06
678
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
10-27
565
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
02-21
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交