Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

197
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda