【问题标题】:return next() in nodejs confusion在nodejs混乱中返回next()
【发布时间】:2015-11-10 20:44:46
【问题描述】:

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()是让流程跳转到下一个中​​间件或函数,但是为什么上面的next()需要return呢?

【问题讨论】:

  • 所以isAuthenticated 返回next() 返回的任何内容。请注意,这可能不是一个有用的值。
  • stackoverflow.com/questions/16810449/… 的可能重复项,但这是一个有效的好问题
  • 在 express 中间件的上下文中,如果该特定的中间件落入其中任何一个 if 语句,它就会停止执行。调用 next 告诉 express '我在这里完成移动' 但是没有 return 它可以调用 next 但也尝试执行重定向。

标签: javascript node.js


【解决方案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() 并且在任何情况下仍然会导致重定向。

【讨论】:

  • 这是在回答问题吗?我知道 next() 做了什么,但为什么要返回 next(),这是我的问题
  • 这正是我在回答中所解释的,是的。只是在此时退出该方法以避免进一步的调用。这是一个模式。它实际上与next() 无关。这主要是因为回调地狱的本质。
猜你喜欢
  • 2015-03-18
  • 1970-01-01
  • 2015-08-06
  • 2020-10-20
  • 2015-08-05
  • 1970-01-01
  • 1970-01-01
  • 2016-09-20
  • 1970-01-01
相关资源
最近更新 更多