Node.js Learning Series (4) - Callback Function

Node.jsThe 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 Nodea large number of callback functions are used, Nodeall of which APIsupport 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/Ooperations. This greatly improves Node.jsthe 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.txtwith the following content:

https://www.baidu.com/

Create a new main.jsfile 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:

insert image description here

non-blocking code

Modify main.jsthe 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:

insert image description here

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.

Guess you like

Origin blog.csdn.net/HH18700418030/article/details/130635670