最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Nodejs difference between 'res.json(..)' and 'return res.json(..)' - Stack Overflow

programmeradmin5浏览0评论

I am learning Nodejs and I do not fully understand the returns. For example, next() in many cases is suggested to be returned in order to make sure execution stop after triggering it (Reference). However, for cases like simple response, is return needed, what is the difference and what is preferred:

res.json({ message: 'Invalid access token' });

vs.

return res.json({ message: 'Invalid access token' });

I am learning Nodejs and I do not fully understand the returns. For example, next() in many cases is suggested to be returned in order to make sure execution stop after triggering it (Reference). However, for cases like simple response, is return needed, what is the difference and what is preferred:

res.json({ message: 'Invalid access token' });

vs.

return res.json({ message: 'Invalid access token' });
Share Improve this question edited May 23, 2017 at 10:34 CommunityBot 11 silver badge asked Jun 9, 2016 at 13:05 eYeeYe 1,7332 gold badges29 silver badges59 bronze badges 4
  • What function is the code above meant to be in? It's impossible to answer the question without that context. – T.J. Crowder Commented Jun 9, 2016 at 13:09
  • The code is for simple authentication function that returns response for authentication attempt. – eYe Commented Jun 9, 2016 at 13:10
  • 3 code below return won't execute :-) Nothing more. I prefer to do not return next() because return statement should be consistent according to this rule – Człowiek Fin Śpiewak Commented Jun 9, 2016 at 13:10
  • @eYe: Show (with specifics), don't tell. – T.J. Crowder Commented Jun 9, 2016 at 13:11
Add a ment  | 

1 Answer 1

Reset to default 15

The return is used to stop execution. It is often used to do some form of early return based on a condition.

Forgetting the return often leads to the function continuing execution instead of returning. The examples are typical express middle-ware examples.

If the middle-ware function looks like this:

function doSomething(req, res, next){
    return res.json({ message: 'Invalid access token' });
}

The resultant behavior would be exactly the same as:

function doSomething(req, res, next){
    res.json({ message: 'Invalid access token' });
}

But very often this pattern is implemented:

function doSomething(req, res, next){
    if(token.isValid){
        return res.json({ message: 'Invalid access token' }); // return is very important here
    }
    next();
}

As you can see here when the return is ommited and the token is invlaid, the function will call the res.json() method but then continue on to the next() method which is not the intended behaviour.

发布评论

评论列表(0)

  1. 暂无评论