The immediate manifestation of node. JS Asynchronous Programming is callback
Asynchronous programming relies on callbacks to implement, but cannot say that the program is asynchronous after using the callback
The callback function is called after the task is completed, and node uses a large number of callback functions, and all node APIs support the callback function
For example, we can read the file while executing other commands, and after the file is read, we return the contents of the file as parameters to the callback function. This will not block or wait for file I/O operations when executing code. This greatly improves the performance of node. JS and can handle a large number of concurrent requests.
Blocking Code Instances
Create a input.txt that reads as follows: (Note save encoding format is UTF-8)
My blog is: http://dapengtalk.blog.51cto.com/
Create callback.js with the following code:
var fs = require (' FS '); var data = Fs.readfilesync (' input.txt '); Console.log (data.tostring ()); Console.log (' End of program execution ');
command line execution, as follows:
650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M02/8A/0E/wKioL1glZbWzD8fCAAAKTqtKVwg548.png "title=" Qq20161111143036.png "alt=" Wkiol1glzbwzd8fcaaaktqtkvwg548.png "/>
Non-blocking code instances:
To modify Callback.js, the code is as follows:
var fs = require (' FS '); Fs.readfile (' Input.txt ', function (err,data) {if (err) {return console.error (err); }else{Console.log (data.tostring ()); }}); Console.log ("program execution ends!");
command line execution, as follows:
650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M01/8A/12/wKiom1glaZjgvnwWAAAKctichrQ842.png "title=" Qq20161111144741.png "alt=" Wkiom1glazjgvnwwaaakctichrq842.png "/>
Above two examples we understand the difference between blocking and non-blocking calls. The first instance finishes executing the program after the file has been read. The second instance we do not need to wait for the file to be read, so that you can read the file while executing the next code, greatly improving the performance of the program.
As a result, blocking is executed sequentially, not blocking is not required in order, so if you need to handle the parameters of the callback function, we need to write in the callback function
Nodejs Study Notes-callback function