CodeWarrior CodeWarrior - 1 year ago 63
Javascript Question

Why code continues to run even after 'return res.send();'

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.


Well, after help of community now discovery and understand that the problem is that return

occur async, in parallel of

In this specific case, the solution is wrap inside

Thanks to @Tom and @PaulPro!

Tom Tom
Answer Source

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

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

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.

I hope that will help.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download