直接上代码:
const PENDING = 'pending'
const FULLFILLED = 'fullfilled'
const REJECTED = 'rejected'
const p = new Promise((resolve,reject)=>{});
class MyPromise{
//executor执行器执行resolve,reject两个回调函数
constructor(executor){
//状态
this.state = PENDING;
//成功的值
this.value = undefined;
//失败的理由
this.reason = undefined;
//池子(成功的池子/失败的池子)
//成功的回调池子
this.onFullFilledCallbacks = []
//失败的回调池子
this.onRejectedCallbacks = []
//成功的回调
const resolve = (value)=>{
if(this.state === PENDING){
this.state = FULLFILLED;
this.value = value;
this.onFullFilledCallbacks.forEach(callback=>callback())
}
}
//失败的回调
const reject = (reason)=>{
if(this.state === PENDING){
this.state = REJECTED;
this.reason = reason;
this.onRejectedCallbacks.forEach(callback=>callback())
}
}
try{
executor(resolve,reject)
}catch(e){
reject(e)
}
}
//实现Promise的then方法,只有成功才能调onFullFilled,失败调用onRejected
//如果还是pending,那么把相关方法追加在池子里
then(onFullFilled, onRejected){
if(this.state === FULLFILLED){
onFullFilled(this.value)
}
if(this.state === REJECTED){
onRejected(this.reason)
}
if(this.state === PENDING){
this.onFullFilledCallbacks.push(()=>{
onFullFilled(this.value)
})
this.onRejectedCallbacks.push(()=>{
onRejected(this.reason)
})
}
}
//失败的时候,拿到一个onRejected函数
catch(onRejected){
if(this.state === REJECTED){
onRejected(this.reason)
}
if(this.state === PENDING){
this.onRejectedCallbacks.push(()=>{
onRejected(this.reason)
})
}
}
}
//MyPromise的一些静态方法
//all方法所有都成功就成功,任何一个失败就失败
MyPromise.all = function(promises){
return new MyPromise((resolve,reject)=>{
let result = [];
let count = 0;
promises.forEach((p, index)=>{
p.then(
(res)=>{
result[index] = res;
count++;
if(count === promises.length){
resolve(result)
}
},
(err)=>{
reject(err)
}
)
})
})
}
//race有一个成功就成功,有一个失败就失败
MyPromise.race = function(promises){
return new MyPromise((resolve,reject)=>{
promises.forEach((p)=>{
p.then(
(res)=>{
resolve(res)
},
(err)=>{
reject(err)
}
)
})
})
}
const pTest = new MyPromise((resolve,reject)=>{
setTimeout(()=>{
// resolve("成功")
reject("失败")
}, 1000)
})
pTest.catch(res=>console.log(res))
// pTest.then((res)=>{
// console.log(res)
// }, (err)=>{
// console.log(err)
// })