Frequently asked questions about callback functions and callback functions

The so-called callback function is to write the second segment of the task in a function alone, and when the task is re-executed, the function is called directly.

fs.readFile('某文件', function (err, data) {
  if (err) throw err;
  console.log(data);
});

This is an error-first callback function (error-first callbacks), which is one of the characteristics of Node.js itself

Common problems with callbacks:

1. Exception handling

try {
   // TODO 
} catch (e){
   // TODO 
}

Asynchronous code try catchno longer works

let async = function(callback){
  try{
    setTimeout(function(){
      callback();
    },1000)
  }catch(e){
    console.log( 'Catch errors' ,e);
  }
}

async(function(){
  console.log(t);
});

Because this callback function is stored and will not be taken out until the next event loop, try can only catch exceptions in the current loop and cannot do anything asynchronously in the face of callback.

Node has a convention in handling exceptions, returning the exception as the first argument of the callback, if it is empty, it means there is no error.

async(function(err,callback){
  if(err){
    console.log(err);
  }
});

Asynchronous methods also follow two principles:

  • The incoming callback function must be called after async
  • If an error occurs, an exception should be passed to the callback function for the caller to judge
let async = function(callback){
try{
  setTimeout(function(){
    if(success)
      callback( null );
     else 
      callback( 'error' );
  },1000)
}catch(e){
  console.log( 'Catch errors' ,e);
}
}

2. Callback area

In the case of asynchronous multi-level dependencies, the nesting is very deep, and the code is difficult to read and maintain

let fs = require('fs');
fs.readFile('template.txt','utf8',function(err,template){
fs.readFile('data.txt','utf8',function(err,data){
  console.log(template+' '+data);
})
})

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324928940&siteId=291194637