报错那里,思来想去不知道=出啥问题了,一直报错
class myPromise{
static PENDING ='待定'
static FULFILLED = "成功"
static REJECTED = "失败"
constructor(func){
this.status=myPromise.PENDING
this.result=null
//4.因为原生promise的resolve在用settimeout包裹,也就是resolve也是异步执行时,then依然会在resolve执行后执行。
//而我们手写的遇到resolve会把它放到宏任务队列稍后执行,这样状态还是pending,then中没有关于状态还是peeding的操作这样then就不会执行了。
//解决办法then中判断状态如果为pending就先把resolve和reject操作放在数组,在resolve执行的时候遍历resolve数组,如果有操作就执行,注意resolve最后执行,所以用sesttimeout再包裹起来
this.resolveCallBacks=[]
this.rejectCallBacks=[]
// 1.func(this.resolve,this.reject)报错,因为resolve和reject是在外部调用的,this不是实例的this
//2.原生promise在传入的函数执行时抛出错误,是可以在then中获取到的,这里是直接执行而不是创建实例后执行,所以不用bind
try {
func(this.resolve.bind(this),this.reject.bind(this))
} catch (error) {
this.reject(error)
}
}
resolve(result){
setTimeout(()=>{
if(this.status===myPromise.PENDING){
this.status=myPromise.FULFILLED
}
this.result=result
this.resolveCallBacks.forEach((callback)=>{
callback(result)
})
})
}
reject(result){
setTimeout(()=>{
if(this.status===myPromise.PENDING){
this.status=myPromise.REJECTED
}
this.result=result
this.rejectCallBacks.forEach((callback)=>{
callback(result)
})
})
}
//then中成功或失败的回调都接受之前resolve或reje的值作为参数
then(onFULFILLED,onREJECTED){
onFULFILLED=typeof onFULFILLED==="function"?onFULFILLED:()=>{}
onREJECTED=typeof onREJECTED==="function"?onREJECTED:()=>{}
if(this.status===myPromise.PENDING){
this.resolveCallBacks.push(onFULFILLED)
this.rejectCallBacks.push(onREJECTED)
}
if(this.status===myPromise.FULFILLED){
//3.setTimeout是异步任务,宏任务,包裹起来让它去任务队列,这样then就可以最后再执行
setTimeout(()=>{
onFULFILLED(this.result)
})
}
if(this.status===myPromise.REJECTED){
setTimeout(()=>{
onREJECTED(this.result)
})
}
}
}
console.log(1)
let test=new myPromise((resolve,reject)=>{
console.log(2)
setTimeout(()=>{
resolve("我成功了")
reject("我失败了")
console.log(4)
})
})
test.then((result)=>{
console.log("成功回调:"+result)
},(result)=>{
console.log("失败回调"+result)
})
console.log(3)
你的 Node.js 版本是?
需要 12+ 才支持 Class Static Fields。否则需要 babel 转换成类似: