Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

195
Views
Hard time to understand this function. Closures, returning function, callback functions

I'm currently building an API and I looked for a way to refactor the async functions so that I don't always have to write try{ } catch(err).... I found this code and there are some things I really do not understand:

module.exports = function (cb) {
  return function (req, res, next) {
    cb(req, res, next).catch(next);
  };
};

First of all why does the returning function gets access to the req, res, next parameters? I think it has something to do with closures, but i can really not see why this works.

Also why do we have to return a function in order to get the parameters? Couldn't we just also use the parameters in the callback function? Like this:

module.exports = function (cb) {
  cb(req, res, next).catch(next);
};

Second, why can we just say ... .catch(next), how does the next() function get access to the error from the catch block without having to pass it in?

Because this is how I would've done it: ... .catch((err) => next(err));

This is how I'm using this function:

exports.getAllTasks = catchAsync(async (req, res, next) => {
  const tasks = await Task.find();

  if (tasks.length === 0) throw new Error('No tasks found');

  res.status(200).json({
    status: 'success',
    results: tasks.length,
    data: {
      tasks,
    },
  });
});
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!