NodeJS, Is it a bad practise to return res.json

后端 未结 3 1619
暖寄归人
暖寄归人 2021-02-08 09:07

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(functi         


        
相关标签:
3条回答
  • 2021-02-08 09:48

    Returning an object in a function don't make additional load.

    0 讨论(0)
  • 2021-02-08 09:50

    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.

    0 讨论(0)
  • 2021-02-08 10:05

    On your exemple, based on callback function, there is no difference. But what if app.get return a Promise ?

    This code will provide an Unhandled rejection Error

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

    This code will not

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

    When using promise always return ;)

    0 讨论(0)
提交回复
热议问题