node.js - callback function

The direct embodiment of Node.js asynchronous programming is callback.

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

The callback function will be called after the task is completed. Node uses a large number of callback functions, and all APIs of Node support callback functions.

For example, we can execute other commands while reading a file. After the file is read, we return the file content as the parameter of the callback function. This way code is executed without blocking or waiting for file I/O operations. This greatly improves the performance of Node.js and can handle a large number of concurrent requests.

The callback function generally appears as the last parameter of the function:

function foo1(name, age, callback) { }
function foo2(value, callback1, callback2) { }

Example of blocking code

Create a file input.txt with the following content:

csdn网站地址:https://blog.csdn.net/jewels_w?type=lately

Create a main.js file with the following code:

var fs = require("fs");

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

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

The above code execution results are as follows:

$ node main.js
csdn网站地址:https://blog.csdn.net/jewels_w?type=lately

程序执行结束!

Example of non-blocking code

Create a file input.txt with the following content:

csdn网站地址:https://blog.csdn.net/jewels_w?type=lately

Create a 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("程序执行结束!");

The above code execution results are as follows:

$ node main.js
程序执行结束!
csdn网站地址:https://blog.csdn.net/jewels_w?type=lately

In the above two examples, we understand the difference between blocking and non-blocking calls. The first instance executes the program after the file has been read. In the second instance, we don't need to wait for the file to be read, so that the next code can be executed while reading the file, which greatly improves the performance of the program.

Therefore, blocking is executed in order, and non-blocking does not need to be in order, so if we need to process the parameters of the callback function, we need to write it in the callback function.

Guess you like

Origin blog.csdn.net/jewels_w/article/details/130624637