0

When I execute the code below:

const https = require('https');

const req = https.get('https://www.google.com', (res) => {
   console.log('message');
})

console.log('message2');

The output I get is:

message2
message

Why is that?

shin
  • 333
  • 3
  • 11
  • 1
    Does this answer your question? [How do you make javascript code execute \*in order\*](https://stackoverflow.com/questions/2637626/how-do-you-make-javascript-code-execute-in-order) – Rashomon Nov 01 '20 at 16:33
  • you need to watch [this video](https://www.youtube.com/watch?v=8aGhZQkoFbQ) to get more understanding of asynchronous behaviour – Naren Nov 01 '20 at 16:34

1 Answers1

0

It's because https.get is asynchronous, so NodeJs don't wait this call and immediately executes console.log('message2');. That way we can not to wait async call completion and continue doing something. After that request finished successfully you'll get console.log('message');

Anatoly
  • 20,799
  • 3
  • 28
  • 42