【发布时间】:2019-11-12 15:35:49
【问题描述】:
我首先尝试创建一个条件语句,因为下面有三个条件,如果其中一个查询未定义,代码会因为错误而停止。
const getEmptyCartQuery = await shopping_cart.findOne({
(...)
});
const needsUpdatedQuantityQuery = await shopping_cart.findOne({
(...)
});
const needsNewCartQuery = await shopping_cart.findOne({
(...)
});
所以我用try-catch语句编写了以下带有异常处理的代码。
const data = await shopping_cart.findAll({
where: { cart_id }
});
try {
const getEmptyCart = await shopping_cart.findOne({ (...) });
if (getEmptyCart) {
await shopping_cart.update({ (...) });
}
ctx.body = data;
} catch (e) {
try {
const needsUpdatedQuantity = await shopping_cart.findOne({ (...) });
if (needsUpdatedQuantity) {
await shopping_cart.update({ (...) });
}
ctx.body = data;
} catch (e) {
try {
const needsNewCart = await shopping_cart.findOne({ (...) });
if (needsNewCart) {
await shopping_cart.create({ (...) });
}
} catch (e) {
ctx.status = 400;
ctx.body = e.message;
}
}
}
它有效,但我可以使用像上面这样的嵌套 try-catch 语句吗?有没有其他方法可以让代码在 db 查找而不是 try-catch 期间无错误地流动?
如果您有任何需要我补充的其他信息,请通过评论或回复告诉我。
谢谢。
【问题讨论】:
标签: javascript node.js ecmascript-6 promise try-catch