本文实例讲述了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程序设计有所帮助。

风云阁资源网 Design By www.bgabc.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
风云阁资源网 Design By www.bgabc.com