NodeJS,返回res.json是否是错误的做法 [英] NodeJS, Is it a bad practise to return res.json

查看:195
本文介绍了NodeJS,返回res.json是否是错误的做法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用NodeJS构建ExpressJS应用程序.我的问题是,如果我这样做

I'm building a ExpressJS application with NodeJS. My question is there any performance difference if I do

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
    });
});

返回res变量会对服务器造成任何额外的负担.两种代码都能正常工作,只是第一个对我来说看起来更好,我节省了一行.

Do returning the res variable make any addition load on the server. Both codes work, just the first looks better to me and I save 1 line.

推荐答案

相反,我认为许多人都会告诉你这种成语是非常合理的做法,因为它使读者(通常是将来的自己)清楚地知道您正在退出).在这种特殊情况下,该策略的优点是可以节省更多代码,因为现在条件分支中只有一条语句,这意味着您可能会花括号.

On the contrary, I think many would tell you this sort of idiom is a very sound practice as it makes clear to the reader (often your future self) that you are exiting). What is very nice about the strategy in this particular case is that you can save a bit more code since you now only have a single statement in your conditional branch, which means you can lose some curly braces.

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

但是您问是否存在性能差异.如果有的话,我认为那几乎是不可察觉的.

But you asked if there was a performance difference. If there is, I think it would be all but imperceptible.

这篇关于NodeJS,返回res.json是否是错误的做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆