Node.js
The direct embodiment of 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, and Node
a large number of callback functions are used, Node
all of which API
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 Node.js
the performance of the server and can handle a large number of concurrent requests.
The callback function generally appears as the last parameter of the function, and the syntax format is as follows:
function foo1(name, age, callback) {
}
function foo2(value, callback1, callback2) {
}
blocking code
Create a new file text.txt
with the following content:
https://www.baidu.com/
Create a new main.js
file with the following code:
var file = require("fs");
var data = file.readFileSync('text.txt');
console.log(data.toString());
console.log("Program End!")
Open the terminal and execute the code:
non-blocking code
Modify main.js
the file and change it to the form of a callback function, as follows:
var file = require("fs");
file.readFile('text.txt',(err,data)=>{
if(err) return console.log('file read err')
console.log('data:',data.toString())
})
console.log("Program End!")
Execute the file again, the execution result is as follows:
As can be seen from the above two examples, blocking is executed in order, while non-blocking does not need to be in order. So if you need to process the parameters of the callback function, you need to write it in the callback function.