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

133
Views
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 answers
Answer question

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 Report
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!