一、then方法中,onFulfilled方法和onRejected方法的调用会生成一个新的promise实例并返回,这两个方法返回的值会存为x
二、保存的x需要进行判断,用于改变新promise实例的状态。
const PENDING = 'pending';
const FULFILLED = 'fulfilled';
const REJECTED = 'rejected';
function resolvePromise(promise2,x,resolve,reject){
console.log(promise2,x)
}
class MPromise{
constructor(excuter){
this.status = PENDING;
this.value = undefined;
this.reason = undefined;
this.onFulfilledCallbacks = []
this.onRejectedCallbacks = []
//声明resole和reject函数,这里用箭头函数可以避免this指向改变,单独方法调用,this指向window或undefined
const resolve = (val) =>{
if(this.status === PENDING){
this.value = val
this.status = FULFILLED
this.onFulfilledCallbacks.forEach((fn)=> fn())
}
}
const reject = (reason) =>{
if(this.status === PENDING){
this.reason = reason
this.status = REJECTED
this.onRejectedCallbacks.forEach((fn)=> fn())
}
}
try{
executor(resolve, reject)
}catch(error){
reject(error)
}
}
//then方法核心部分是,判断promise当前status,做出不同操作
//function class里面添加原型方法,不用写function关键字
then(onFulfilled, onRejected){
let promise2 = new Promise((resolve,reject)=>{
//如果是pending状态,收集相关方法,等状态改变时再调用
if(this.status === PENDING){
//之前搜集回调时,没有传value和reason
this.onFulfilledCallbacks.push(()=>{
try{
let x = onFulfilled(this.value)
}catch(error){
reject(error)
}
})
this.onRejectedCallbacks.push(()=>{
try{
let x = onRejected(this.reason)
}catch(error){
reject(error)
}
})
}
if(this.status === FULFIILED){
setTimeout(()=>{
try{
let x = onFulfilled(this.value)
//这里要将新promise实例传到函数中,但是此处是在new Promise的executor中
//需要将onFulfilled和onRejected写成异步方法,可以写成宏任务或者微任务,
//源码中写成了微任务
resolvePromise(promise2,x,resolve,reject)
}catch(error){
reject(error)
}
},0)
}
if(this.status === REJECTED){
setTimeout(()=>{
try{
let x = onRjected(this.reason)
resolvePromise(promise2,x,resolve,reject)
}catch(error){
reject(error)
}
},0)
}
})
return promise2
}
}