CodeWarrior CodeWarrior - 2 months ago 6
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.

UPDATE:

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

res.send();
occur async, in parallel of
console.log()
.

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

Thanks to @Tom and @PaulPro!

Tom Tom
Answer

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

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

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.