NodeJS,返回res.json是不好的做法

我正在用NodeJS构build一个ExpressJS应用程序。 我的问题是,如果我这样做有任何性能差异

app.get('/test', function(req, res) { fn(function(err, data) { if (err) { return res.json(400, { error: 1, msg: "some error" }); } ///more code }); }); 

代替

 app.get('/test', function(req, res) { fn(function(err, data) { if (err) { res.json(400, { error: 1, msg: "some error" }); return; } ///more code }); }); 

是否返回resvariables使服务器上的任何加载负载。 两个代码工作,只是第一个看起来更好,我保存1行。

相反,我想很多人会告诉你,这种习惯用法是非常正确的做法,因为它向读者(通常是你的未来的自己)表明你正在退出)。 在这种情况下,策略的好处是可以节省更多的代码,因为现在在条件分支中只有一条语句,这意味着您可能会丢失一些花括号。

 app.get('/test', function(req, res) { fn(function(err, data) { if (err) return res.json(400, { error: 1, msg: "some error" }); ///more code }); }); 

但你问是否有性能差异。 如果有的话,我认为这将是不可感知的。

在函数中返回一个对象不会产生额外的负载。

在你的例子中,基于callback函数,没有区别。 但是,如果app.get返回一个Promise呢?

此代码将提供未处理的拒绝错误

 app.get('/test') .then( (data) => { /* do something with your data that can throw a functional error for exemple request for a user on your database based on your data */ if (!user) res.json(401, {msg: 'USER NOT FOUND'}); if (user.someProperty) //will throw an error when user is not found res.json(200, {msg: 'USER DID IT'}); }) .catch( (err) => { res.json(500, {msg: 'OUTCH'}); throw(err); }); 

这段代码不会

 app.get('/test') .then( (data) => { /* do something with your data that can throw a functional error for exemple request for a user on your database based on your data */ if (!user) return res.json(401, {msg: 'USER NOT FOUND'}); if (user.someProperty) //will not be evaluate when user is not found return res.json(200, {msg: 'USER DID IT'}); }) .catch( (err) => { res.json(500, {msg: 'OUTCH'}); throw(err); }); 

使用诺言时总是返回;)