javascript node.js next()

Harry picture Harry · Mar 21, 2011 · Viewed 120.7k times · Source

I see a lot of use next in node.js.

What is it, where does it come from? What does it do? Can I use it client side?

Sorry it's used for example here: http://dailyjs.com/2010/12/06/node-tutorial-5/

look for the loadUser function.

Answer

Wayne picture Wayne · Mar 21, 2011

This appears to be a variable naming convention in Node.js control-flow code, where a reference to the next function to execute is given to a callback for it to kick-off when it's done.

See, for example, the code samples here:

Let's look at the example you posted:

function loadUser(req, res, next) {
  if (req.session.user_id) {
    User.findById(req.session.user_id, function(user) {
      if (user) {
        req.currentUser = user;
        return next();
      } else {
        res.redirect('/sessions/new');
      }
    });
  } else {
    res.redirect('/sessions/new');
  }
}

app.get('/documents.:format?', loadUser, function(req, res) {
  // ...
});

The loadUser function expects a function in its third argument, which is bound to the name next. This is a normal function parameter. It holds a reference to the next action to perform and is called once loadUser is done (unless a user could not be found).

There's nothing special about the name next in this example; we could have named it anything.