class MPromise = {
state = 'pending' // 3. promise的状态 'pending' 'fulfilled' 'rejected'
value = undefined // 成功之后的值
reason = undefined // 失败之后的值
resolveCallbacks = [] // then方法pedding状态下,存储成功的回调函数
rejectCallbacks = [] // then方法pedding状态下,存储失败的回调函数
// 1.传入一个参数 fn
constructor(fn) {
// fn里面分别是resolve 和 reject 的方法
const resolveHandler = (value) => {
if(this.state === 'pending') {
this.state = 'fulfilled'
this.value = value
// 执行存储的成功的回调函数
this.resolveCallbacks.forEach( fn => fn(this.value) )
}
}
const rejectHandler = (reason) => {
if(this.state === 'pending') {
this.state = 'rejected'
this.reason = reason
// 执行存储的失败的回调函数
this.rejectCallbacks.forEach( fn => fn(this.reason) )
}
}
try{
// 2.这里执行了fn方法, promise在new的时候就执行它里面的方法(这是我自己理解的)
fn(resolveHandler, rejectHandler)
}catch(err){
rejectHandler(err)
}
}
// 4. .then 方法
// 因为promise里面有可能是异步,那么这个时候then就不确定执行那个方法且当前状态是pending,这个时候就要把这两个fn1, fn2给保存起来
then(fn1, fn2) {
// 第一步 判断fn1,fn2 是否是函数
fn1 = typeof fn1 === 'function' ? fn1 : (v) => v
fn2 = typeof fn2 === 'function' ? fn2 : (e) => e
// 第二步 状态判断 无论是什么状态他都返回一个新的promise
if(this.state === 'pending') {
const p1 = new MPromise((resolve, reject) => {
// 存储
this.resolveCallbacks.push(()=> {
try {
const newValue = fn1(this.value)
resolve(newValue)
} catch(err) {
reject(err)
}
})
this.rejectCallbacks.push(()=> {
try {
const newReason = fn2(this.reason)
reject(newReason)
} catch(err) {
reject(err)
}
})
})
return p1
}
if(this.state === 'fulfilled') {
const p1 = new MPromise((resolve, reject) => {
// 用try catch 规避传入的fn1的语法错误
try {
const newValue = fn1(this.value)
resolve(newValue)
} catch(err) {
reject(err)
}
})
return p1
}
if(this.state === 'rejected') {
const p1 = new MPromise((resolve, reject) => {
// 用try catch 规避传入的fn1的语法错误
try {
const newReason = fn2(this.reason)
resolve(reason)
} catch(err) {
reject(err)
}
})
return p1
}
}
// catch 就是 then 的语法糖
catch(fn) {
return this.then(null, fn)
}
}