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)
该返回值用于停止执行。它通常用于根据条件进行某种形式的提前归还。
忘记返回通常会导致函数继续执行而不是返回。这些示例是典型的快速中间件示例。
如果中间件功能如下所示:
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()方法,这不是预期的行为。
归档时间: |
|
查看次数: |
1230 次 |
最近记录: |