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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With