Search code examples
javascriptnode.jsexpresserror-handlingasync-await

what does express-async-handler do?


Hey I am trying to comprehend what does express-async-handler do?

It was used in one of the repo I was looking.

From their docs, it says

Simple middleware for handling exceptions inside of async express routes and passing them to your express error handlers.

Link for the repo: https://www.npmjs.com/package/express-async-handler

Can someone please explain this with example?


Solution

  • The example in the npm page shows this:

    express.get('/', asyncHandler(async (req, res, next) => {
        const bar = await foo.findAll();
        res.send(bar)
    }))
    

    Without asyncHandler you'd need:

    express.get('/',(req, res, next) => {
        foo.findAll()
        .then ( bar => {
           res.send(bar)
         } )
        .catch(next); // error passed on to the error handling route
    })
    

    or using async/await:

    express.get('/', async (req, res, next) => {
        try {
            const bar = await foo.findAll();
            res.send(bar);
        } catch (err) {
            next(err); // error passed on to the error handling route
        }
    });
    

    With the library, no catch is needed to call next() if an error is thrown within the route.