node. JS callback function
The callback function generally appears as the last parameter of the function:
function foo1 (name, age, callback) {}function Foo2 (value, Callback1, Callback2) {}
Blocking Code Instances
Create a file input.txt with the following content:
Beginner's Tutorial official website address: www.runoob.com
Create the Main.js file with the following code:
var fs = require ("FS"); var data = 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 Novice Tutorial Official website address: www.runoob.com program execution end!
Non-blocking Code instances
Create a file input.txt with the following content:
Beginner's Tutorial official website address: www.runoob.com
Create the Main.js file with the following code:
var fs = require ("FS"); Fs.readfile (' Input.txt ', function (err, data) { if (err) return Console.error (err); Console.log (Data.tostring ());}); Console.log ("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.
Excerpt from: http://www.runoob.com/nodejs/nodejs-callback.html
node. JS callback function