【问题标题】:Javascript: Using try-catch nestingJavascript:使用 try-catch 嵌套
【发布时间】: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


    【解决方案1】:

    你可以使用Promise.all:

    Promise.all([shopping_cart.findOne({ ... }), shopping_cart.findOne({ ... }), shopping_cart.findOne({ ... })])
      .then(data => { /* Everything worked! */ })
      .catch(err => { /* There was an error */ });
    

    【讨论】:

      【解决方案2】:

      使用@Jack Bashford 的解决方案,如果你更喜欢处理 async/await 的写法,你可以写同样的语句:

      try {
        const [result1, result2, result3] = await Promise.all([
            shopping_cart.findOne({ ...}),
            shopping_cart.findOne({ ...}),
            shopping_cart.findOne({ ...})
        ]);
        // use the results
      } catch (error) {
        // catch the error
      }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-19
        • 2016-08-08
        • 1970-01-01
        • 1970-01-01
        • 2020-01-15
        • 1970-01-01
        • 1970-01-01
        • 2017-04-22
        相关资源
        最近更新 更多