skip to Main Content

As for a simple example, in this two sample code here, how is a next() a parameter and how can
it be executed to automatically go to the next middleware function? How does this work behind the abstraction?

app.use((req, res, next) => {
  console.log('Time:', Date.now())
  next()
});

app.use((req, res, next) => {
  console.log('Time2:', Date.now())
  next()
});

This outputs:
Time: (Now’s date)
Time2: (Now’s date)

This is done from top to bottom.

2

Answers


  1. next will be a closure that contains a reference to the array of middlewares and the current index (or some equivalent data). So when you call it, it increments the index and calls that middleware’s function. Each call to next() steps through all the middlewares until it gets to the end.

    Login or Signup to reply.
  2. This is done from top to bottom.

    Not necessarily. What happens is that app.use() collects the middlewares in an array. Then when a request comes in, the router goes through that array and can create the respective next callback for each middleware so that it will run the remaining handlers. The router also selects the middlewares according to path, method, etc if you have restricted them – which you didn’t in your example.

    Here’s a small demo:

    function app(req, res, last) {
      const run = app.middlewares.reduceRight((nextStep, middleware) => {
        const step = (err) => {
          // if (err) …
          middleware(req, res, nextStep);
        };
        return step;
      }, last);
      run();
    }
    app.middlewares = [];
    app.use = function(middleware) {
      app.middlewares.push(middleware);
    };
    
    app.use((req, res, next) => {
      console.log('Time:', Date.now())
      next()
    });
    app.use((req, res, next) => {
      console.log('Time2:', Date.now())
      next()
    });
    
    app({}, {}, () => console.log('last'));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search