Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

198
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda