为什么代码在'return res.send();'之后仍然继续运行 [英] Why code continues to run even after 'return res.send();'

查看:687
本文介绍了为什么代码在'return res.send();'之后仍然继续运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么代码在返回并调用res.send()后仍继续运行。这是一个 GIST ,以帮助理解。

I don't understand why code continues to run even after return and res.send() was called. This is a GIST to help to understand.

更新:

好了,在社区帮助后现在发现并了解问题是返回 res.send(); console.log()并行发生异步。

Well, after help of community now discovery and understand that the problem is that return res.send(); occur async, in parallel of console.log().

在这种特定情况下,如果/ else ,解决方案将包含在中。

In this specific case, the solution is wrap inside if/else.

感谢@Tom和@PaulPro!

Thanks to @Tom and @PaulPro!

推荐答案

嗨!如果您使用以下代码段,则会在控制台上打印文本(请注意<$ c旁边没有返回 $ c> res.send )。

The Hi! text is printed on the console if you use following code snippet (note there is no return next to res.send).

app.get('/asd', function (req, res) {
  res.send('OK');
  console.log('Hi!');
});

以下代码段不会打印嗨!在控制台上,请求处理函数随 res.send('OK')结束; 表达式

Following code snippet will not print Hi! on the console as the request handling function ends along with res.send('OK'); expression

app.get('/asd', function (req, res) {
  return res.send('OK');
  console.log('Hi!');
});

您可以看到 Hi!在第一个实例中, res.send 函数是异步执行的,即方法发送响应在JavaScript事件循环中排队,请求处理函数继续执行并调用 console.log 嗨!参数。

The reason why you can see Hi! in the first instance is that the res.send function is performed asynchronously i.e. method sending response is queued in the JavaScript event loop and the request handling function continue execution and calls console.log with Hi! argument.

我希望能帮助。

这篇关于为什么代码在'return res.send();'之后仍然继续运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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