简体   繁体   中英

Javascript: Using try-catch nesting

I am trying to create a conditional statement first because there are three conditions below, and if one of those queries is undefined, the code stops because of an error.

const getEmptyCartQuery = await shopping_cart.findOne({
  (...)
});
const needsUpdatedQuantityQuery = await shopping_cart.findOne({
  (...)
});
const needsNewCartQuery = await shopping_cart.findOne({ 
  (...)
});

So I wrote the following code with exception handling with a try-catch statement.

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;
      }
    }
  }

It works, but can I use a nested try-catch statement like above? Is there any other way that the code can flow without errors during db lookup instead of try-catch?

Please let me know by comment or reply if you have any additional information I need to supplement.

Thank you.

You could use Promise.all :

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

Using the solution of @Jack Bashford, if you prefer to deal with async/await way of write, you can write the same statement like that:

 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 } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM