我正在使用Restify和Nodejs,我有一个关于将控制权返回到堆栈中下一个中间件的正确方法的问题.当我说"堆栈中的下一个中间件"时,我希望我使用正确的短语.
基本上,我的代码看起来像这样:
//server is the server created using Restify
server.use(function (req, res, next) {
//if some checks are a success
return next();
});
Run Code Online (Sandbox Code Playgroud)
现在,我想知道的是代码应该return next();或者应该只是next();将控制传递给堆栈中的下一个?
我检查了两个工作 - 这两段代码都会成功传递控制并按预期返回数据 - 我想知道的是两者之间是否存在差异,如果我需要使用另一个.
rob*_*lep 18
没有区别.我看了一下Restify源代码,它似乎根本没有对中间件的返回值做任何事情.
使用的原因return next()纯粹是为了方便:
// using this...
if (someCondition) {
return next();
}
res.send(...);
// instead of...
if (someCondition) {
next();
} else {
res.send(...);
};
Run Code Online (Sandbox Code Playgroud)
它可能有助于防止这样的错误:
if (someCondition)
next();
res.send(...); // !!! oops! we already called the next middleware *and* we're
// sending a response ourselves!
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6396 次 |
| 最近记录: |