Express JS 对请求使用异步函数 [英] Express JS use async function on requests
问题描述
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);
}
});
问题是.使用 async 函数能够使用 await 进行 DB 查询可以吗?我担心它会导致 expressjs 方面出现一些问题.
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 可以毫无问题地用于数据库查询.您可以使用 try catch 但是有一个更优雅的解决方案,它允许您使用 express 提供的错误处理中间件:
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
})
这篇关于Express JS 对请求使用异步函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!