CodeWarrior CodeWarrior - 4 months ago 17
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

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.