I am relatively new to async await and am wondering if I should use await on operations where I am not returning any values. For example ..
should I
const deleting_info = await pool.query('DELETE where...');
or should I
pool.query('DELETE WHERE...')
I feel like I should use the second one but I am not sure and have not been able to find an answer. My understanding is that I can continue through faster without using the await key word. Please help. Thank you.
CodePudding user response:
You seem to be forgetting about error logging and error handling and sending a different response to the http request based on whether the operation succeeded or failed.
At a minimum, you must listen for errors on your database calls so you don't have unhandled rejections and so you can log any error and probably influence the returned status from the incoming http request.
You can do that with an await
surrounded by a try/catch
where you get the error in the catch
block or you can just use a .catch()
. If you don't really care when it's done and don't want to wait for completion before doing anything else, then at a minimum, use a .catch()
.
pool.query('DELETE WHERE...').catch(e => {
console.log(e);
// do something to handle the error (such as send an error status back from the request)
});
You don't show the whole context of the request handler, but usually, you would send a success 2xx status if the database operation completes properly and send an error status (probably 5xx) if you have a database error. So, in that case, you need either both a .then()
and .catch()
or an await
with try/catch
around it so you can distinguish success from non-success.
try {
await pool.query('DELETE where...');
res.sendStatus(200);
} catch(e) {
// log the error and send error status in response
console.log(e);
res.sendStatus(500);
}