简体   繁体   中英

console.log printing statements in the wrong order for learnyounode node.js tutorial

I'm making a GET request, storing the data, and then noting the response is over. I have one console.log statement for when I'm done receiving the data and another for when the program has finished. See below:

var a = 1
var b = 10e9

http.get(process.argv[2], function(response){
  response.pipe(bl())
  response.on('end', function(){
    console.log("Finished receiving data")
  })
})

while(a != b){
  a++
}

console.log("Program has finished")

In this case, I would expect the order of the print statements to be

Finished receiving data
Program has finished

because I would expect the end of the response to occur before the while loop terminates. However, regardless of whether that loop is 1 to 2 or 1 to 100000000000, I always get

Program has finished
Finished receiving data

Why are the print statements happening in this order?

For all of the fuss about its asynchronous expressivity, node.js is single threaded and will only have one thread of execution per process - that means only one line of code will be executed at a time.

When you make the asynchronous call to http.get , node.js sends off an HTTP GET and defers execution of the callback until (1) the callback is ready to be called and (2) it runs out of synchronous (blocking) code to run. This explains why you always see "Program is finished" first - node.js has finished executing its blocking code and is ready to move on to handling the asynchronous callback that contains "Finished receiving data" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM