Recently I wrote some node scripts, and I feel that the callback function is a big pit, which is briefly summarized here.
The most direct manifestation of node asynchronous programming is callback
The difference between synchronous and asynchronous: Blocking occurs when reading file information synchronously, but not asynchronously.
1. Callback for reading and writing files (asynchronous)
var fs=require("fs") //Introduce the fs module var fileName = "./haha" // file path // start synchronization var data = fs.readFileSync(fileName); console.log(data.toString) //Convert the read file into a string Another way to convert to string var data = fs.readFileSync(fileName,{flag: 'r+', encoding: 'utf8'}) console.log(data) // start asynchronously fs.readFile(__dirname + '/test.txt', {flag: 'r+', encoding: 'utf8'}, function (err, data) { if(err) { console.error(err); return; } console.log(data); });
2, add the callback parameter to the function to call back
var a=0;
(1) The simplest kind of callback function
function setNumber(cb) { var a=1; var b=a+1; cb(b) } function getNumber(data) { console.log(data) } setNumber (getNumber)
(2) I am raising a chestnut
function findByStaId(staId,cb) { getMongosData({staId: staId},function (result) { //call a function if (!result[0]) { cb({status: false}) } cb({status: true, stationConfig: result[0]} }) } findByStaId(staId,function(result){ console.log(result) })