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

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

问题描述

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

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

我的理解是 res.send 't 返回功能,但是关闭连接/结束请求。这可以解释为什么我仍然可以在 res.send 命令之后执行代码(我看过明文源码,似乎不是一个异步函数)。



有没有其他的东西可能会丢失?

解决方案

p>确定结束结束HTTP响应,但对代码没有任何特殊的处理。



你可以继续做其他的事情,即使你已经结束了回应。



然而,你不能/ />做任何有用的事情 RES 。由于响应结束,您无法向其中写入更多数据。

  res.send(...); 
res.write('more stuff'); //抛出一个错误,因为res现在被关闭

此行为与其他传统框架(PHP,ASP等),它将线程分配给HTTP请求,并在响应结束时终止线程。如果您调用ASP的 Response.End 等效函数,则线程将终止,代码将停止运行。在节点中,没有线程可以停止。 req res 不会再触发任何事件,但回调中的代码可以自由继续运行只要不尝试调用 res 方法,需要有效的响应才能打开。


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

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

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?

解决方案

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.

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

This behavior is unlike other traditional frameworks (PHP, ASP, etc) which allocate a thread to a HTTP request and 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天全站免登陆