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

141
Visualizações
How can I add an async middleware to a router route

I have an expresss router, and I'm configuring some routes for it, I pass a validator for the data and a handler, but the validator has to work with some promises so I need to place an await, the code that I wrote looks like this:

constructor() {
    this.router = express.Router();
    this.router.use(express.json());
    this.router.use(express.text({ type: ['text/plain', 'text/html'] }));
  }

  async addCreateTaskRoute(validator, handler) {
    if (!handler) {
      throw Error('cannot add empty handler');
    }

    this.router.post('/tasks', await validator, handler);

    return this;
  }

Does this solution look alright to you? Are there any other options? The project that this is included in is a middleware, and the validator and handlers come from other modules and the type of them is express RequestHandler

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Your validator should call next() asynchronously after successful validation, this will then invoke the next middleware, which is handler. After unsuccessful validation, an error is returned and next() is not called so that no further middlewares are processed.

async function validator(req, res, next) {
  var valid = await validationResult(...);
  if (valid) next();
  else res.status(400).end("Error message");
}
this.router.post("/tasks", validator, handler);
about 4 years ago · Juan Pablo Isaza Relatório
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