我们希望减少 Promise 中的 catch block 的数量。如果我们删除嵌套的 catch,异常会冒泡到父 catch 吗?
temporaryUserModel.findOne({email: req.body.email})
.then(tempUser => {
if (tempUser) {
temporaryUserModel.findOneAndUpdate({_id: tempUser.toJSON()._id}, user)
.then((doc) => {
return res.status(200).json({
status: 'Success',
data: {url: planOpted.chargifySignupUrl}
});
})
.catch(err => error(err, res));
} else {
temporaryUserModel(user).save()
.then((doc) => {
return res.status(200).json({
status: 'Success',
data: {url: planOpted.chargifySignupUrl}
});
})
.catch(err => error(err, res));
}
})
.catch(err => error(err, res));
我们想删除两个嵌套的 catch 并仅保留底部的 catch。这样可以吗?
最佳答案
不,他们不会。如果您链接您的 promise ,它们只会冒泡到结果 promise ,为此您需要返回
由回调创建的内部 promise 。否则,外部 promise 无法等待它们,并且不知道它们何时/如何解决(无论它们履行还是拒绝)。
temporaryUserModel.findOne({email: req.body.email}).then(tempUser => {
if (tempUser) {
return temporaryUserModel.findOneAndUpdate({_id: tempUser.toJSON()._id}, user);
// ^^^^^^
} else {
return temporaryUserModel(user).save();
// ^^^^^^
}
}).then((doc) => {
// no need to duplicate this code when you chain anyway
return res.status(200).json({
status: 'Success',
data: {url: planOpted.chargifySignupUrl}
});
}).catch(err => error(err, res));
关于javascript - 是否需要在 promise 内嵌套捕获?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41336812/