Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
435 views
Welcome To Ask or Share your Answers For Others

1 Answer

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 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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...