The first step in explaining this involves creating a problem, here’s the scenario: You’re running a site like gist.github.com and you need to fetch some meta data for a list of gists from the server. This is going to involve you making multiple requests and then doing something when they’re all finished, you’ll probably want a loading spinner overlay or something while it fetches them as well.

The way to do this in an elegant way is to have something execute a set of functions or requests that can each tell the central component when they have finished. I’m going to create a very simple class called Batch that will do just that.

/** * Executes a list of functions that call back when they are finished. * * @class * @param {Array} functions Target methods to execute when requested. * @param {Function} completionHandler Executed when all target functions are finished. */ function Batch(functions, completionHandler) { this._functions = functions; this._completionHandler = completionHandler; }