0

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.

2 Answers 2

1

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 */ });
Sign up to request clarification or add additional context in comments.

Comments

0

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
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.