trasherdk / hyper-express

High performance Node.js webserver with a simple-to-use API powered by uWebsockets.js under the hood.
MIT License
0 stars 0 forks source link

Snippet: Synchornous middlewares and asynchronous middlewares difference #19

Open trasherdk opened 1 year ago

trasherdk commented 1 year ago

As stated in Middlewares.md you can have two types of middlewares. Synchornous middlewares and Asynchronous middlewares.

Asynchronous middlewares you do NOT need to call next() as the request will continue once your middleware async resolves. So for example:

Asynchronous middleware:

app.use(async (req, res) => {
  // This will happen first
  await some_operation_1(req);

  // This will happen second
  await some_operation_2(req);

  /*
   * Since you have no more code below and this callback resolves,
   * HyperExpress will automatically continue to the next middleware/handler as long as you did not send a response.
   */
})

If you want to use next() then you must make your middleware synchronous like so: Synchronous middleware:

app.use((req, res, next) => {
   some_operation_1(req) // Happens first
   .then(() => some_operation_2(req)) // Happens second
   .then(() => next()); // Proceed to the next middleware/handler because you explicitly called next()
})

Source: https://github.com/kartikk221/hyper-express/issues/140#issuecomment-1328093601