Nodejs difference between 'res.json(..)' and 'return res.json(..)'

eYe*_*eYe 1 javascript syntax node.js

我正在学习Nodejs,但我并不完全了解回报。例如,next()建议在许多情况下返回以确保执行在触发后停止(参考)。但是,对于诸如简单响应之类的情况是return必需的,有什么区别和首选:

res.json({ message: 'Invalid access token' });
Run Code Online (Sandbox Code Playgroud)

return res.json({ message: 'Invalid access token' });
Run Code Online (Sandbox Code Playgroud)

Chr*_*rbe 5

该返回值用于停止执行。它通常用于根据条件进行某种形式的提前归还。

忘记返回通常会导致函数继续执行而不是返回。这些示例是典型的快速中间件示例。

如果中间件功能如下所示:

function doSomething(req, res, next){
    return res.json({ message: 'Invalid access token' });
}
Run Code Online (Sandbox Code Playgroud)

结果行为将与以下内容完全相同:

function doSomething(req, res, next){
    res.json({ message: 'Invalid access token' });
}
Run Code Online (Sandbox Code Playgroud)

但是通常会实现此模式:

function doSomething(req, res, next){
    if(token.isValid){
        return res.json({ message: 'Invalid access token' }); // return is very important here
    }
    next();
}
Run Code Online (Sandbox Code Playgroud)

如您在这里看到的,当省略返回值并插入令牌时,该函数将调用res.json()方法,然后继续执行next()方法,这不是预期的行为。

  • 是的,从技术上讲你不必这样做,我尝试在调用回调时始终返回。它只是消除了很多总是返回这个的调试时间。不止一次地调用回调,最终以泪水告终。:( (2认同)