node. JS callback function
The immediate manifestation of node. JS asynchronous programming is callbacks.
Asynchronous programming relies on callbacks to implement, but it cannot be said 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.
The following is an example of blocking code and non-blocking code, respectively. The contents of the TXT file used in the two pieces of code are as follows:
I ' m file.txt.
Blocking code
var fs = require ("FS"); var data = Fs.readfilesync (' file.txt '); Console.log (data.tostring ()); Console.log ("over");
In the above code, Fs.readfilesync represents the synchronous execution of the read file operation, which blocks the main process so that the main process can continue after the file is read, and the result is as follows
G:\nodejs>node Server.jsi'm file.txtover
Non-blocking code
var fs = require ("FS"); Fs.readfile (thefunction (err, data) {if return console.error (err); Console.log (Data.tostring ());}); Console.log ("over");
Note: The error function prints incorrect information in the console.
The above code, when reading the file using a callback function, so that the main process to ensure that the continuation of execution, and the child process only after the completion of all the necessary work, the callback function will be called, the specific output is as follows:
G:\nodejs>node Server.jsoveri' m file.txt
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 performed 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.
"Node. JS learning Four" node. JS callback function