node. JS is an event-driven, non-blocking I/O model used to build fast, extensible network applications.
The problem that node. JS wants to solve is: process input, input, high concurrency
1. Blocking and non-blocking
Blocking is also called synchronization, which means that each time an operation is performed, the execution of the code is blocked and cannot be moved to the next operation until the operation is completed.
blocking is the equivalent of you in the supermarket to buy things, checkout, in line, if the front of the people did not pay, you can not buy, must wait for the front of the people to perform their operations before they can
non-blocking is the equivalent of you in the grandmother's home to take the number, and then you can do other things, waiting for our turn, the text message sent to our mobile phone, said it is our turn, so we can go back to dinner.
functionSleep (milliseconds) {varStart =NewDate (). GetTime (); while((NewDate (). GetTime ()-Start <milliseconds) { }}functionFetchpage () {Console.log (' Fetching page '); Sleep (2000);//simulate time to query a databaseConsole.log (' data returned from requesting page ');}functionFetchapi () {Console.log (' Fetching API '); Sleep (2000);//simulate time to fetch from the An APIConsole.log (' data returned from the API ');} Fetchpage (); Fetchapi ();
The result of executing the above code is as follows:
node. JS rarely uses this coding style, but instead calls callbacks asynchronously
What is a callback? a callback refers to passing a function A as a parameter to another function B, and is usually called after function B is complete.
1. Asynchronous invocation is done by the operating system in the background.
2. The synchronized code will continue to execute
3. When the operating system completes asynchronously, call the callback function to display the corresponding results
varHTTP = require (' http ')functionFetchpage () {Console.log (' Fetching page '); Http.get ({host:' Trafficjamapp.herokuapp.com ', Path: '/?delay=2000 '},function(res) {Console.log (' data returned from requesting page '); }). On (' Error ',function(e) {Console.log ("There is an error" +e); });}functionFetchapi () {Console.log (' Fetching API '); Http.get ({host:' Trafficjamapp.herokuapp.com ', Path: '/?delay=2000 '},function(res) {Console.log (' data returned from the API '); }). On (' Error ',function(e) {Console.log ("There is an error" +e); });} Fetchpage (); Fetchapi ();
The result of non-blocking (asynchronous) code execution is as follows:
Node. JS Learning Notes under Windows (4)---the concept of synchronous, asynchronous, callback