0

I have multiple Node-mssql module requests for mssql-database inside an async function in Javascript...

What is the best method to generally wait for the results and check if all of them passed? The requests kind of belong together, so they have to pass all together or if one fails, then all fail.

let result1 = await requestObject.query(someQuery);
let result2 = await requestObject.query(otherQuery);

Normally, I use a .then().catch clause,

.then((result) => res.status(200).send(result)).catch(err => res.status(404).send(err)); 

but I want to avoid this because I have 2 queries and I can only use it on my last query because after sending a response I cannot send another response.

what's the best way to check if the return status of both my queries was OK or if an error happened? because they are executed kind of synchronously in the above order.

I think my approaches would either be:

  1. I could check result1 and result2 for some status code or if they are not empty (depending on my query?)
  2. I would do a .then() Promise-chain, where I execute my second query inside the .then()-block of the first resulted query, and at the end I do a .catch(), so it should automatically catch all errors that occured during any query, is that right?
MMMM
  • 3,320
  • 8
  • 43
  • 80
  • 3
    `Promise.all()`. The `.catch()` chained to it will trigger on the first error, no matter which promise inside the array triggered it. – Shilly Jun 12 '19 at 14:21

1 Answers1

1

You can do a try/catch:

try {
   let result1 = await requestObject.query(someQuery);
   let result2 = await requestObject.query(otherQuery);
   // now you have both results, do something
}
catch (err) {
   // if one of them fails
   console.log(err)
}
sigmus
  • 2,987
  • 3
  • 23
  • 31
  • ok thanks, thats all? thats quite simple, it will automatically catch any errors that occur during the requests? But my other methods were OK, too? Right? – MMMM Jun 12 '19 at 14:21
  • Yes, please note this: https://stackoverflow.com/questions/46515764/how-can-i-use-async-await-at-the-top-level – sigmus Jun 12 '19 at 14:22
  • thanks, I noticed some interesting IIFE code: `(async () => { var text = await main(); console.log(text); })().catch(e => { // Deal with the fact the chain failed });` could I also use it like this to execute it immediately and automatically return me the results in a then clause as soon as I got the results? `(async () => { var text = await main(); console.log(text); })().then(result=> doSomething()).catch(e => console.log(e)) });` – MMMM Jun 12 '19 at 14:30