Nodejs difference between 'res.json(..)' and 'return res.json(..)'

余生颓废 提交于 2020-01-01 19:50:48

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/37726863/nodejs-difference-between-res-json-and-return-res-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!