1. 程式人生 > >node.js實現回撥

node.js實現回撥

向回撥函式傳遞額外的引數

        在呼叫函式中,使用匿名函式中實現需傳遞的引數,再次匿名函式內呼叫回撥函式。

  1. var events =require("events");
  2. functionCarShow(){
  3. events.EventEmitter.call(this);
  4. this.seeCar =function(make){
  5. this.emit('sawCar', make);
  6. }
  7. }
  8. CarShow.prototype.__proto__ = events.EventEmitter.prototype;
  9. var show =newCarShow();
  10. function logCar(make
    ){
  11. console.log("Saw a "+make);
  12. }
  13. function logColorCar(make, color){
  14. console.log("Saw a %s %s ", color, make);
  15. }
  16. show.on("sawCar", logCar);
  17. show.on("sawCar",function(make){
  18. var colors =["red","blue","black","pink","green"];
  19. var color = colors[Math.floor(Math.random()*3)];
  20. logColorCar(make, color);
  21. });
  22. show.seeCar("Ferrari");
  23. show.seeCar("Porsche");
  24. 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. for(var idx in cars){
  14. var msg ="Saw a "+cars[idx];
  15. (function(msg){
  16. logCar(msg,function(){
  17. console.log("Closure Callback "+ msg);
  18. })
  19. })(msg);
  20. }
  21. //Normal Callback Saw a 朗逸
  22. //Normal Callback Saw a 朗逸
  23. //Normal Callback Saw a 朗逸
  24. //Closure Callback Saw a 獵豹
  25. //Closure Callback Saw a 捷達
  26. //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. function logCars(cars){
  10. var car = cars.pop();
  11. logCar(car,function(){
  12. logCars(cars);
  13. });
  14. }
  15. var cars =["獵豹","捷達","朗逸"];
  16. logCars(cars);