为什么我可以在“res.send"之后执行代码? [英] Why can I execute code after "res.send"?

查看:36
本文介绍了为什么我可以在“res.send"之后执行代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道以下代码行为背后的机制是什么:

I'm wondering what the mechanics behind the behaviour of the following code are:

res.send(200, { data: 'test data' });
console.log('still here...');

我的理解是res.send 不会返回函数,而是关闭连接/结束请求.这可以解释为什么我仍然可以在 res.send 命令之后执行代码(我查看了 express 源代码,它似乎不是一个异步函数).

My understanding is that res.send doesn't return the function, but does close the connection / end the request. This could explain why I can still execute code after a res.send command (I looked through the express source and it doesn't seem to be an asynchronous function).

还有什么我可能遗漏的东西吗?

Is there something else at play that I may be missing?

推荐答案

当然 end 会结束 HTTP 响应,但它不会对您的代码做任何特殊处理.

Sure end ends the HTTP response, but it doesn't do anything special to your code.

您可以在结束回复后继续做其他事情.

You can continue doing other things even after you've ended a response.

不能做的是,用res做任何有用的事情.由于响应已结束,您无法再向其中写入更多数据.

What you can't do, however, is do anything useful with res. Since the response is over, you can't write more data to it.

res.send(...);
res.write('more stuff'); // throws an error since res is now closed

这种行为与其他传统框架(PHP、ASP 等)不同,后者为 HTTP 请求分配一个线程并在响应结束时终止该线程.如果您调用 ASP 的 Response.End 等等效函数,线程将终止并且您的代码停止运行.在节点中,没有要停止的线程.reqres 不会再触发任何事件,但是回调中的代码可以继续运行(只要它不尝试调用 res 需要有效响应才能打开).

This behavior is unlike other traditional frameworks (PHP, ASP, etc) which allocate a thread to a HTTP request and terminate the thread when the response is over. If you call an equivalent function like ASP's Response.End, the thread terminates and your code stops running. In node, there is no thread to stop. req and res won't fire any more events, but the code in your callbacks is free to continue running (so long as it does not attempt to call methods on res that require a valid response to be open).

这篇关于为什么我可以在“res.send"之后执行代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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