Node.js callback function
Node.js The direct manifestation of asynchronous programming is callbacks.
Asynchronous programming relies on callbacks, but it cannot be said that the program becomes asynchronous after using callbacks.
The callback function will be called after completing the task. Node uses a large number of callback functions. All Node APIs support callback functions.
For example, we can read a file while executing other commands. After the file reading is completed, we return the file content as a parameter of the callback function. This way there is no blocking or waiting for file I/O operations while executing code. This greatly improves the performance of Node.js and can handle a large number of concurrent requests.
Blocking code example
Create a file input.txt with the following content:
php中文网官网地址:www.php.cn
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("程序执行结束!");
The above code execution results are as follows:
$ node main.js php中文网官网地址:www.php.cn 程序执行结束!
Non-blocking code example
Create a file input.txt with the following content:
php中文网官网地址:www.php.cn
Create the main.js file, The code is 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 execution result of the above code is as follows:
$ node main.js 程序执行结束! php中文网官网地址:www.php.cn
We have learned the difference between blocking and non-blocking calls in the above two examples. The first instance finishes executing the program after the file has been read. In the second example, we do not need to wait for the file to be read, so that the next code can be executed at the same time as the file is read, which greatly improves the performance of the program.
Therefore, blocking is executed in order, but 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.