简体   繁体   中英

Node.js request - order of execution

So I am new to Node development. My first personal project requires creating a local txt file of the html contents of a page for further manipulation. I don't know why everything else in the program is executed before the request call is made. For example in the below snippet, "Two" will always come before "One". I know it is probably something simple I am missing but I am hoping to learn something from it.

 var request = require('request'); var fs = require('fs'); request('https://www.google.com', function (response, body) { console.log("One") fs.writeFile("ToParse.txt", body) }); console.log("Two") 

"Two" will always come before "One"

Because Node.js is asynchronous

What it does mean than previous function won't stop the execution process instead the functions are called irrespective of previous function has stopped execution

If you want a sequence use Callbacks or Promises

This is because of the async nature of nodejs/JavaScript because it's single Threaded, Request module is performing asynchronous operation and aftering completion or failure of the operation, it will call the last function which we call a callback function.

Request will take time to perform it's operation while doing a get method to www.google.com

Node will put that operation in queue and execute the other operation, in your case console.log it consoles the result and later from the queue it will execute the queued operation.

Visit this https://developer.mozilla.org/en/docs/Web/JavaScript/EventLoop

The callback function first parameter should always be error, if no error occurs it will be null.

request('http://www.google.com', function (error, response, body) {
   // your code
})

The function you passed as the second argument to the function request is a callback. It will be called once the request processed. The nature of Node.js is, to execute codes continuously without waiting(blocked) for the callback to be called. When the request completes(fails/succeeds) your callback will be called. That's why "Two" printed before "One"

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