Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 807
anny123 Avatar asked Jan 01 '23 19:01

anny123


2 Answers

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

The first one uses the async / await language elements and is more concise.

like image 158
2 revs, 2 users 97% Avatar answered Jan 12 '23 02:01

2 revs, 2 users 97%


You have to install npm package --> npm i express-async-handler.

//import package
const asyncHandler = require("express-async-handler");

//when using async handler
//wrap the async function with asynchandler
//like this asyncHandler(async fn())
const getRequest = asyncHandler(async (req, res) => {
if(req.body.xxxx)
{
   const response = await db.collection.find();
   res.status(200).send("success");
}
else{
   res.status(400).send("failed");
//we can simply throw error like this
   throw new Error("Something went wrong")
}

})

No need to worry about returning try catch blocks.

like image 33
Arunkumar R Avatar answered Jan 12 '23 02:01

Arunkumar R