Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 436
Thales P Avatar asked Feb 12 '14 22:02

Thales P


2 Answers

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.

like image 99
Tom Avatar answered Sep 22 '22 10:09

Tom


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!

like image 36
Thales P Avatar answered Sep 22 '22 10:09

Thales P