Advertisement
Guest User

Chaining call backs

a guest
Oct 30th, 2014
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //With asynchronous functions, you are not guranteed the order in which they will fun if two are palced 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
  2.  
  3. function logCar(car, callback){
  4.   console.log("Saw a %s", car);
  5.   if(cars.length){
  6.     process.nextTick(function(){
  7.       callback();
  8.     });
  9.   }
  10. }
  11. function logCars(cars){
  12.   var car = cars.pop();
  13.   logCar(car, function(){
  14.     logCars(cars);
  15.   });
  16. }
  17. var cars = ["Ferrari", "Porsche", "Bugatti", "Lamborghini", "Aston Martin"];
  18. logCars(cars);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement