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(); //or return next();
}
});
Issue: I am checking which one to go with just next()
or return next()
. Above sample code works exactly the same for both & did not show any difference in execution.
Question: Can some one put light on this, when to use next()
and when to use return next()
and some important difference?
next()
is part of connect middleware. Callbacks for router flow doesn't care if you return anything from your functions, soreturn next()
andnext(); return;
is basically the same.In case you want to stop the flow of functions you can use
next(err)
like the followingPretty much
next()
is used for extending the middleware of your requests.As @Laurent Perrin's answer:
I give an example here if you write middleware like this:
You will find out that the output in console is:
That is, it runs the code below next() after all middleware function finished.
However, if you use
return next()
, it will jump out the callback immediately and the code belowreturn next()
in the callback will be unreachable.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:
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.