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

140
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
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