Nodejs'res.json(..)'和'return res.json(..)'之间的区别 [英] Nodejs difference between 'res.json(..)' and 'return res.json(..)'

查看:818
本文介绍了Nodejs'res.json(..)'和'return res.json(..)'之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 Nodejs ,我不完全理解这些回报。例如,建议在很多情况下返回 next(),以确保在触发后停止执行(参考)。但是,对于简单响应等情况,需要 return ,有什么区别和首选:

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


推荐答案

返回用于停止执行。它通常用于根据条件进行某种形式的早期返回。

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

正如您在此处看到的那样,当返回被忽略并且令牌被激活时,该函数将调用res.json()方法,但继续执行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.

这篇关于Nodejs'res.json(..)'和'return res.json(..)'之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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