Chaining Callbacks

With asynchronous functions, you are not guaranteed the order in which they will run if two are placed on the event queue. The best way to resolve this is to implement callback chaining by having the callback from the asynchronous function call the function again until there is no more work to do. That way, the asynchronous function is never on the event queue more than once.

The code in Listing 4.7 implements a very basic example of callback chaining. A list of items is passed into the function logCars(), and then the asynchronous function logCar() is called, and the logCars() function is used as the callback when logCar() completes. Thus only one version of logCar() is on the event queue at a time. Figure 4.10 shows the output of iterating though the list.

Listing 4.7 callback_chain.js: Implementing a callback chain where the callback from an anonymous function calls back into the initial function to iterate through a list


01 function logCar(car, callback){
02   console.log("Saw a %s", car);
03   if(cars.length){
04     process.nextTick(function(){
05       callback();
06     });
07   }
08 }
09 function logCars(cars){
10   var car = cars.pop();
11   logCar(car, function(){
12     logCars(cars);
13   });
14 }
15 var cars = ["Ferrari", "Porsche", "Bugatti",
16             "Lamborghini", "Aston Martin"];
17 logCars(cars);


Image

Figure 4.10 Output of callback_chain.js, showing how to use an asynchronous callback chain to iterate through a list.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.38.8