在nodejs混淆中返回next()

时间:2015-11-10 12:22:25

标签: javascript node.js

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');
};

为什么作者会return next()代替next()?我知道next()是让流程跳转到下一个中​​间件或函数,但为什么它需要return上面的next()

1 个答案:

答案 0 :(得分:1)

预设return以退出该功能是一种惯例。另一种方法是使用if-else if-else而不是if。在这种情况下,您只想退出该功能并在中间件链上继续前进。

你会经常看到这种模式。例如,这很常见:

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

    console.log(result);
});
与此相比,它的嵌套更少,读取更容易:

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

第一种模式还可以防止您意外调用next()两次甚至更多次,以防您的if-else - 逻辑出现错误。 在您发布的情况下,next()确实不应该发生这种情况。它可以调用next()并仍然导致任何重定向情况下。