node. js example method for implementing callback

  • 2021-07-26 06:02:36
  • OfStack

This paper illustrates the method of node. js to realize callback. Share it for your reference, as follows:

Pass extra arguments to the callback function

In the calling function, the callback function is called in the anonymous function again using the parameters that need to be passed in the implementation of the anonymous function.


var events = require("events");
function CarShow() {
  events.EventEmitter.call(this);
  this.seeCar = function (make) {
    this.emit('sawCar', make);
  }
}
CarShow.prototype.__proto__ = events.EventEmitter.prototype;
var show = new CarShow();
function logCar(make) {
  console.log("Saw a "+make);
}
function logColorCar(make, color) {
  console.log("Saw a %s %s ", color, make);
}
show.on("sawCar", logCar);
show.on("sawCar", function (make) {
  var colors = ["red", "blue", "black", "pink", "green"];
  var color = colors[Math.floor(Math.random()*3)];
  logColorCar(make, color);
});
show.seeCar("Ferrari");
show.seeCar("Porsche");
show.seeCar("Bugatti");

Implementing closures in callbacks

If a callback function needs to access the variables in the scope of the parent function, it needs to use closures to encapsulate an asynchronous call inside the function block and pass in the required variables.


function logCar(logMsg, callback) {
  process.nextTick(function () {
    callback(logMsg);
  });
}
var cars = [" Cheetah ", " Jetta ", " Langyi "];
for(var idx in cars){
  var msg = "Saw a "+cars[idx];
  logCar(msg, function () {
    console.log("Normal Callback "+ msg);
  });
}
for(var idx in cars){
  var msg = "Saw a "+cars[idx];
  (function (msg) {
    logCar(msg, function () {
      console.log("Closure Callback "+ msg);
    })
  })(msg);
}
//Normal Callback Saw a  Langyi 
//Normal Callback Saw a  Langyi 
//Normal Callback Saw a  Langyi 
//Closure Callback Saw a  Cheetah 
//Closure Callback Saw a  Jetta 
//Closure Callback Saw a  Langyi 

Chain callback

When using asynchronous functions, there is no guarantee that both functions will run in order if they are on the event queue. The workaround is to have the callback from an asynchronous function call the function again until there is no more work to do to perform the chained callback.


function logCar(car, callback) {
  console.log("Saw a %$", car);
  if(cars.length){
    process.nextTick(function () {
      callback();
    });
  }
}
function logCars(cars) {
  var car = cars.pop();
  logCar(car, function () {
    logCars(cars);
  });
}
var cars = [" Cheetah ", " Jetta ", " Langyi "];
logCars(cars);

I hope this article is helpful to everyone's nodejs programming.


Related articles: