Stuck on understanding asyncHandler on Nodejs

Viewed 2171

I am currently stuck on understanding how asyncHandler really works. I understand that asyncHandler is a wrapper method for controller methods so that we don't have to write try/catch on every method that we call on controller or services/repo (that is a good dry). I also understand that async/await returns promises so

return Promise.resolve(fn(req, res, next)).catch(next);

is acting as a try/catch. below is the full script of asynchandler

var asyncHandler = function (fn) {
 return function (req, res, next) {
   return Promise.resolve(fn(req, res, next)).catch(next);
 };
};

module.exports = asyncHandler;

what I dont understand is how return function(req,res,next) is working?

1 Answers

It's actually comes to understanding the closure in Javascript. When you call asyncHandler and pass the "fn" argument to it, it actually returns a callable function that will work as a common Express controller function, therefore will have req, res, and next as common arguments. asyncHandler itself is just a function returning other function. For example

const controller = function(req, res, next) { 
  // do some stuff
}
counts wrappedController = asyncHander(controller)
router.use('/', wrappedController)

You basically wrap your controller function into another one, so when asyncHandler gets called it returns other common function, but saves some variables - controller in that case ("fn" argument), into closure. When you trigger '/' and wrappedController gets called it just calls previously saved variable - controller function taking it from closure.

Related