当前位置:首页 >> 网络编程

node.js实现回调的方法示例

本文实例讲述了node.js实现回调的方法。分享给大家供大家参考,具体如下:

向回调函数传递额外的参数

在调用函数中,使用匿名函数中实现需传递的参数,再次匿名函数内调用回调函数。

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");

在回调中实现闭包

如果某个回调函数需要访问父函数的作用域的变量,就需要使用闭包,在函数块内部封装一个异步调用,并传入所需要的变量。

function logCar(logMsg, callback) {
  process.nextTick(function () {
    callback(logMsg);
  });
}
var cars = ["猎豹", "捷达", "朗逸"];
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 朗逸
//Normal Callback Saw a 朗逸
//Normal Callback Saw a 朗逸
//Closure Callback Saw a 猎豹
//Closure Callback Saw a 捷达
//Closure Callback Saw a 朗逸

链式回调

使用异步函数时,如果两个函数都在事件队列上,则无法保证它们的运行顺序。解决方法是让来自异步函数的回调再次调用该函数,直到没有更多的工作要做,以执行链式回调。

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 = ["猎豹", "捷达", "朗逸"];
logCars(cars);

希望本文所述对大家nodejs程序设计有所帮助。