node.js实现回调

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

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


  
  
  1. var events = require("events");
  2.  
  3. function CarShow() {
  4. events.EventEmitter.call(this);
  5. this.seeCar = function (make) {
  6. this.emit('sawCar', make);
  7. }
  8. }
  9. CarShow.prototype.__proto__ = events.EventEmitter.prototype;
  10. var show = new CarShow();
  11.  
  12. function logCar(make) {
  13. console.log("Saw a "+make);
  14. }
  15.  
  16. function logColorCar(make, color) {
  17. console.log("Saw a %s %s ", color, make);
  18. }
  19.  
  20. show.on("sawCar", logCar);
  21. show.on("sawCar", function (make) {
  22. var colors = ["red", "blue", "black", "pink", "green"];
  23. var color = colors[Math.floor(Math.random()*3)];
  24. logColorCar(make, color);
  25. });
  26. show.seeCar("Ferrari");
  27. show.seeCar("Porsche");
  28. show.seeCar("Bugatti");

在回调中实现闭包

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


  
  
  1. function logCar(logMsg, callback) {
  2. process.nextTick(function () {
  3. callback(logMsg);
  4. });
  5. }
  6. var cars = ["猎豹", "捷达", "朗逸"];
  7. for(var idx in cars){
  8. var msg = "Saw a "+cars[idx];
  9. logCar(msg, function () {
  10. console.log("Normal Callback "+ msg);
  11. });
  12. }
  13.  
  14. for(var idx in cars){
  15. var msg = "Saw a "+cars[idx];
  16. (function (msg) {
  17. logCar(msg, function () {
  18. console.log("Closure Callback "+ msg);
  19. })
  20. })(msg);
  21. }
  22. //Normal Callback Saw a 朗逸
  23. //Normal Callback Saw a 朗逸
  24. //Normal Callback Saw a 朗逸
  25. //Closure Callback Saw a 猎豹
  26. //Closure Callback Saw a 捷达
  27. //Closure Callback Saw a 朗逸

链式回调

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


  
  
  1. function logCar(car, callback) {
  2. console.log("Saw a %$", car);
  3. if(cars.length){
  4. process.nextTick(function () {
  5. callback();
  6. });
  7. }
  8. }
  9.  
  10. function logCars(cars) {
  11. var car = cars.pop();
  12. logCar(car, function () {
  13. logCars(cars);
  14. });
  15. }
  16.  
  17. var cars = ["猎豹", "捷达", "朗逸"];
  18. logCars(cars);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值