因为catch和then的第二个参数,是处理rejected状态的,但是它默认返回的应该是resolved啊。老师这里reject(newReason);不是又返回rejected的状态吗?
还有如果老师我这样理解是对的话pending里面该怎么改呢?
then(fn1, fn2) {
// 判断fn1, fn2是不是函数
fn1 = typeof fn1 === 'function' ? fn1 : (v) => v;
fn2 = typeof fn2 === 'function' ? fn2 : (e) => e;
if (this.state === 'pending') {
// 当pending状态下,fn1和fn2会存储到callbacks中
return new MyPromise((resolve, reject) => {
this.resolveCallbacks.push(() => {
try {
const newValue = fn1(this.value);
resolve(newValue);
} catch (error) {
reject(error);
}
})
this.rejectCallbacks.push(() => {
try {
const newReason = fn2(this.reason);
reject(newReason);
} catch (error) {
reject(error);
}
})
})
}
if (this.state === 'fulfilled') {
// 要返回新的promise,传入当前的value,计算出新的value,resolve
return new MyPromise((resolve, reject) => {
try {
const newValue = fn1(this.value);
resolve(newValue);
} catch (error) {
reject(error);
}
})
}
if (this.state === 'rejected') {
// 要返回新的promise,传入当前的reason,生成新的reason,reject
return new MyPromise((resolve, reject) => {
try {
const newValue = fn2(this.reason);
resolve(newValue); **//这里改为resolve**
} catch (error) {
reject(error);
}
})
}
}
// 就是then的语法糖
catch(fn) {
return this.then(null, fn);
}