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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access