关于catch返回的问题
来源:8-20 手写 Promise-then 的链式调用

慕移动6312711
2021-11-25
老师,目前封装的catch的返回值,只能通过catch链式调用,而实际上promise.catch的返回值只要不出现类似throw 的错误,应该返回resolve状态,可以通过.then接受的,我在.then方法this.state === 'rejected’里面对代码进行了修改是实现了这个方法和去掉了this.state === 'pending’的验证是实现这个需求的,不知道这样有没有问题。
// 构造函数中的内容
const rejectFn = (reason) => {
// if(this.state === 'pending'){ 去掉了这个验证
this.reason = reason
this.state = 'rejected'
this.rejectCallbacks.forEach((item)=>item(item.reason))
// }
}
//then 方法的内容
if(this.state === 'rejected'){
return new MyPromise((resolve,reject)=>{
try {
const newReason = fn2(this.reason)
resolve(newReason) // reject 改为了 resolve
} catch (error) {
reject(error)
}
})
}
写回答
1回答
-
双越
2021-11-26
去掉了,你需要多验证一个问题:状态变化是不可逆的,不能允许 fulfilled 变为 rejected
00
相似问题