CALLBACK:A callback is A function so is passed as an argument to another function and is executed after its parent func tion has completed.
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.
Blocking Code Instances
Create a file input.txt with the following content:
Novice Tutorial Official website address:www. Runoob. COM
Create the Main.js file with the following code:
var=require("FS"); var= fs. Readfilesync(' input.txt '); Console. Log(data. ToString()); console. Log("program execution ends!") );
The result of the above code execution is as follows:
$ node main. JS Rookie Tutorial official website address:www. Runoob. COM program execution ends!
Non-blocking Code instances
Create a file input.txt with the following content:
Novice Tutorial Official website address:www. Runoob. COM
Create the Main.js file with the following code:
VarFs= Require("FS");Fs.ReadFile(' Input.txt ', function (Err, Data) {if (err return Console.err Console.< Span class= "PLN" >log (data. Tostringconsole. ( "program execution ends!"
The result of the above code execution is as follows:
$ node main. JS program execution end! Novice Tutorial Official website address:www. Runoob. COM
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. In the second instance, we don't have to wait for the file to be read, so we can execute the next code while reading the file, which greatly improves 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 it inside the callback function.
node. JS callback function