Node .js callback function

Node .js the direct embodiment of asynchronous programming is callbacks.

Asynchronous programming relies on callbacks, but it cannot be said that the program is asynchronous after a callback is used.

Callback functions are called when they are completed, Node uses a large number of callback functions, and all node APIs support callback functions.

For example, we can read the file while executing other commands, and when the file is read, we return the contents of the file as an argument to the callback function. T his way, there is no blocking or waiting for file I/O operations when the code is executed. This greatly improves the performance .js node system, which can handle a large number of sympo-requests.


Block code instances

Create a file input .txt as follows:

W3Cschool教程官网地址:www.w3cschool.cn

Create a main .js file, code as follows:

var fs = require("fs");

var data = fs.readFileSync('input.txt');

console.log(data.toString());
console.log("程序执行结束!");

The above code executes as follows:

$ node main.js
W3Cschool教程官网地址:www.w3cschool.cn

程序执行结束!

Non-blocking code instances

Create a file input .txt as follows:

W3Cschool教程官网地址:www.w3cschool.cn

Create a main .js file, code as follows:

var fs = require("fs");

fs.readFile('input.txt', function (err, data) {
    if (err) return console.error(err);
    console.log(data.toString());
});

console.log("程序执行结束!");

The above code executes as follows:

$ node main.js
程序执行结束!
W3Cschool教程官网地址:www.w3cschool.cn

In both instances, we understand the difference between blocking and non-blocking calls. T he first instance does not complete the program until the file has been read. The second instance we do not need to wait for the file to finish reading, so that we can read the file at the same time to execute the next code, greatly improving the performance of the program.

Therefore, blocking is performed sequentially, not in order, so if we need to handle the parameters of the callback function, we need to write them in the callback function.