Express JS对请求使用异步功能 [英] Express JS use async function on requests

查看:440
本文介绍了Express JS对请求使用异步功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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);
    }
});

问题是.使用异步功能能够将等待用于数据库查询可以吗?恐怕这可能会在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.

推荐答案

异步等待可以毫无问题地用于数据库查询.您可以使用try catch,但是有一个更优雅的解决方案,该解决方案使您可以使用提供以下内容的错误处理中间件:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆