Return next () in nodejs confusion

https://github.com/hwz/chirp/blob/master/module-5/completed/routes/api.js

function isAuthenticated (req, res, next) { // if user is authenticated in the session, call the next() to call the next request handler // Passport adds this method to request object. A middleware is allowed to add properties to // request and response objects //allow all get request methods if(req.method === "GET"){ return next(); } if (req.isAuthenticated()){ return next(); } // if the user is not authenticated then redirect him to the login page return res.redirect('/#login'); }; 

Why does the author do return next() instead of next() ? I know that next() allows the thread to jump to the next middleware or function, but why does it return for next() above?

+5
source share
1 answer

This is the convention of adding return to exit the function. An alternative would be to use if-else if-else instead of just if . In this case, you just want to exit the function and move on through the middleware chain.

You will see this pattern quite often. For example, this is pretty common:

 someFunction(function(err, result) { if (err) { return console.error(err); } console.log(result); }); 

This is less nesting and easier to read for most poeple compared to this:

 someFunction(function(err, result) { if (err) { console.error(err); } else { console.log(result); } }); 

The first pattern also prevents you from accidentally calling next() twice or even more times if you have some error in your if-else -logic. And this is exactly what should not happen to next() , in which case you sent. It could call next() and still call the redirect anyway.

+1
source

Source: https://habr.com/ru/post/1235613/


All Articles