Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Understanding next middle-ware in the scope of express.js / sail.js controller

Understanding next middle-ware in the scope of express.js / sail.js controller

Problem

I am using sails.js which is built on top of express.js . In my routes.js I defined a route like following

'/account/login': {
      controller    : 'Session',
      action        : 'logInAPI'
  },

And my session Controller is like this

logInAPI: function(req, res, next) {
        if (!req.param('email') || !req.param('password')) {

            var usernamePasswordRequiredError = [
                'You must enter a username and a password.'
            ]

            req.session.flash = {
                err: usernamePasswordRequiredError
            }

            return next();
                }
            else{// Log in user};
  }

I am wondering when I am calling next where does it pointing to in middlewear. What will happen if just write return; Instead of return next();

Problem courtesy of: Muhammad Raihan Muhaimin

Solution

The reason you call next() instead of just returning some value is to allow asynchronous serial chaining of middleware operations. For example:

function(req, res, next){
  setTimeout(next, 1000);
}

This is an example of a useless middleware that does nothing except delay the response for one second. Note specifically that in this case, next() executes after the function returns.

In a more realistic scenario, setTimeout() would of course be replaced by some logic that does a database fetch and accepts a callback, for example.

Solution courtesy of: greim

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Understanding next middle-ware in the scope of express.js / sail.js controller

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×