Looping Callback Pattern

December 04, 2012

Node.js is really fast. We use it to run various APIs and low level HTTP tools in a very high traffic environment. It can be a bit of a mind bender getting your head round callback / event based programming. One of the patterns I often forget is a function which loops over a dataset, calling an asynchronous function which needs wait until all the callbacks have been fired before returning a result. This needs to be done in an asynchronous, non blocking manner.

Here is a real world example in coffeescript.

The main concept to be grasped here is that a results array is maintained and the final callback occurs only when the results array is the same size as the dataset which is being looped through. (In this case the mos object.)

There may well be a cleaner way to do this, if so please let me know in the comments!