Latest web development tutorials

Node.js callback function

Directly reflects Node.js asynchronous programming is the callback.

Relying on callback asynchronous programming to achieve, but can not say that after using the callback of the asynchronous program.

The callback function will be called after the completion of the task, Node uses a lot of callbacks, Node API supports all callback functions.

For example, we can read the file side, while the implementation of other commands, after reading the document is complete, we will file contents as an argument to the callback function returns. In the performance of code are not blocked or waiting for file I / O operations. This greatly improves the performance of Node.js can handle a large number of concurrent requests.


Blocking code examples

Create a file input.txt, reads as follows:

本教程官网地址:www.w3big.com

Create main.js file, as follows:

var fs = require("fs");

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

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

The above code is executed as follows:

$ node main.js
本教程官网地址:www.w3big.com

程序执行结束!

Non-blocking code examples

Create a file input.txt, reads as follows:

本教程官网地址:www.w3big.com

Create main.js file, 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 is executed as follows:

$ node main.js
程序执行结束!
本教程官网地址:www.w3big.com

We understand the above two examples of different blocking and non-blocking calls. After the first instance of the file is read before executing the program. The second instance we do not need to wait to read the complete file, so that the next code can be executed at the same time while reading the file, greatly improving the performance of the program.

Thus, by blocking it is executed sequentially, while non-blocking is not required in order, so if you need to handle the callback function parameter, we need to write in the callback function.