Express JS use async function on requests

前端 未结 3 2077
花落未央
花落未央 2020-11-28 15:52
app.use(async function(req, res, next) {
    try {
        var myres = await new Promise((resolve, reject) => {
            mysql_connection.query(\"select * from         


        
3条回答
  •  忘掉有多难
    2020-11-28 16:35

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

提交回复
热议问题