只是简单的实现Promise部分功能,.catch和.finally以及类方法都没有实现,感兴趣的可以再继续深入研究
// 简单手写部分Promise
const PROMISE_STATUS_PENGING = "pending"
const PROMISE_STATUS_FULFILLED = "fulfilled"
const PROMISE_STATUS_REJECTED = "rejected"
class myPromise{
// 构造函数接收Promise回调,回调接收两个参数在构造函数里定义
constructor(executor){
//状态管理,执行了resolve就不执行reject
this.status = PROMISE_STATUS_PENGING
// 存放resolve和reject传的参数
this.value = undefined
this.reason = undefined
const resolve = (value)=>{
// 状态判断
if(this.status === PROMISE_STATUS_PENGING){
this.status = PROMISE_STATUS_FULFILLED
console.log("执行");
queueMicrotask(()=>{ //微任务延迟执行 setTimeout为宏任务
this.value = value
console.log("resolve被执行");
if(this.onFulfilled){
this.onFulfilled(this.value)
}
})
}
}
const reject = (reason)=>{
if(this.status === PROMISE_STATUS_PENGING){
this.status = PROMISE_STATUS_REJECTED
queueMicrotask(()=>{
this.reason = reason
console.log("reject被执行");
if(this.onRejected){
this.onRejected(this.reason)
}
})
}
}
// 执行Promise
executor(resolve,reject)
}
// 绑定resolve和reject后要执行的函数,在上述微任务执行之前已绑定
then(onFulfilled,onRejected){
this.onFulfilled = onFulfilled
this.onRejected = onRejected
}
}
const p = new myPromise((resolve,reject)=>{
// 执行了resolve就不执行reject验证
resolve("成功")
reject("失败")
})
console.log(1111);
// .then属于主线程任务,执行then后才开始执行上行resolve内的微任务
p.then(res=>{
console.log('res: ', res);
},err=>{
console.log('err: ', err);
})
打印结果