async function(req, res) {
try {
const user = await userCtrl.getUser();
const userMaps = await mapsCtrl.findDetails(user.mapId);
res.send(userMaps);
} catch (error) {
//handle error
res.status(400).send(error)
}
}
// user controll
function getUser() {
return new Promise(function(resolve, reject) {
//data base read using mysql
req.app.get("mysqlConn").query(query, function(error, results, fields) {
if (error) {
reject(error);
}
resolve(results);
});
})
}
//maps controller function is also like above one.
This is the code handle part of an express get route. Sometimes the rejected code is not getting caught. I get the error returned from MySQL in 200 status code.
Yes you can write multiple awaits in a single try catch block. so your catch block will receive the error if any of the above await fails. Refer this link for more information about async-await - https://javascript.info/async-await
reject() or resolve () doesn't mean the functions is terminated. So we have to explicitly return from the function to avoid further code execution. In your case put resolve in else block or just put return statement in the if block after the reject is called! Refer this link for more information:- Do I need to return after early resolve/reject?
I hope this help :) Regards.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With