Scenario: Consider the following is the part of code from a node web app.
app.get('/users/:id?', function(req, res, next){
var id = req.params.id;
if (id) {
// do something
} else {
next();
}
});
Issue: I am checking which one to go for just next() or return next(). For the above code sample both the codes works exactly the same way did not show any difference in execution part.
Question: Can some one put light of when to use next() and when to use return next() and some important difference?
Some people always write return next() is to ensure that the execution stops after triggering the callback.
If you don't do it, you risk triggering the callback a second time later, which usually has devastating results. Your code is fine as it is, but I would rewrite it as:
app.get('/users/:id?', function(req, res, next){
var id = req.params.id;
if(!id)
return next();
// do something
});
It saves me an indentation level, and when I read the code again later, I'm sure there is no way next is called twice.
next() is part of connect middleware. Callbacks for router flow doesn't care if you return anything from your functions, so return next() and next(); return; is basically the same.
In case you want to stop the flow of functions you can use next(err) like the following
app.get('/user/:id?',
function(req, res, next) {
console.log('function one');
if ( !req.params.id )
next('No ID'); // This will return error
else
next(); // This will continue to function 2
},
function(req, res) {
console.log('function two');
}
);
Pretty much next() is used for extending the middleware of your requests.