app.use(async function(req, res, next) {
try {
var myres = await new Promise((resolve, reject) => {
mysql_connection.query("select * from Users;", (err, rows) => {
if (err) {
reject(err);
} else {
resolve(rows);
}
});
});
} catch (error) {
console.log(error);
}
});
Question is. using async function to be able to use await for DB queries is ok? i am afraid that it can cause some problems on expressjs side.
解决方案
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
})