When programming in JavaScript (or CoffeeScript) you sometimes face a
situation where you need to complete multiple independant asynchronous
methods before continuing. This situation crops up in web browsers but
its much more common when writing server-side JavaScript, e.g. with
Node.js - for example you might need to fetch from a
database, fetch from a KVS,
read a file and perform a remote HTTP request before outputting the
compiled information to the end user.
One method of solving this issue is to chain the asynchronous calls, however this
means that they’re run one after the other (serially) - and thus it will
take longer to complete them. A better way would be to run them in
parallel and have something track their completion. This is exactly what
my very simple AsyncBatch class does:
.coffee.jsAsyncBatch class, triggers event once all wrapped callbacks complete
###Create a new AsyncBatch instance###batch = newAsyncBatch###Wrap your callbacks with batch.wrap and a nameThe name is used to store the result returned by your callback(Don't forget to return the result you're interested in!)###delay50,batch.wrap'timer',->return"Timer complete"###Add a completion handler that accepts `results` as a parameter. `results` is a JS object where the keys are the callback names from above and the values are the return values of the callbacks.###batch.on'done',(results) ->console.log"Batch complete, timer result: #{results.timer}"
NOTE: If your asynchronous method accepts both a success and
failure callback then simply wrap both individually but
ensure you use the same name for both.
NOTE: Other than the case in the previous NOTE, all callbacks
should have different names.
A full example (including a stub EventEmitter implementation) follows:
An example of how to use AsyncBatch to handle parallel callbacks in Node.JS (async-batch.coffee)download