app.use(async function(req, res, next) {
try {
var myres = await new Promise((resolve, reject) => {
mysql_connection.query(\"select * from
Async await can be used with no problem for DB queries. You could use try catch however there is a more elegant solution which allows you to use the error handling middleware which express offers:
You wrap your middleware with this function:
const asyncMiddleware = fn =>
(req, res, next) => {
Promise.resolve(fn(req, res, next))
.catch(next);
};
Then you can use it in the following manner:
const asyncMiddleware = require('./utils/asyncMiddleware');
router.get('/', asyncMiddleware(async (req, res, next) => {
/*
if there is an error thrown in getUserFromDb, asyncMiddleware
will pass it to next() and express will handle the error;
*/
const user = await getUserFromDb({ id: req.params.id })
res.json(user);
}));
If an error is thrown the control will be handed over to the error handling middleware which is middlware which has four arguments like this:
app.use(function (err, req, res, next) {
// your error code
})