Passing in Async functions to Node.js Express.js router

前端 未结 5 2054
别跟我提以往
别跟我提以往 2021-02-04 05:37

This seems like a straightforward google, but I can\'t seem to find the answer...

Can you pass in ES7 async functions to the Express router?

Example:

<         


        
5条回答
  •  无人共我
    2021-02-04 06:14

    It sort of works, but not really

    While it seems to work, it stops handling errors thrown inside the async function, and as a result, if an error is not handled, the server never responds and the client keeps waiting until it timeout.

    The correct behavior should be to respond with a 500 status code.


    Solutions

    express-promise-router

    const router = require('express-promise-router')();
    
    // Use it like a normal router, it will handle async functions
    

    express-asyncify

    const asyncify = require('express-asyncify')
    

    To fix routes set in the app object

    Replace var app = express(); with

    var app = asyncify(express());
    

    To fix routes set in router objects

    Replace var router = express.Router(); with

    var router = asyncify(express.Router());
    

    Note

    You only need to apply the asyncify function in the objects where you set the routes directly

    https://www.npmjs.com/package/express-asyncify

提交回复
热议问题