jQuery.when – Sometimes it’s the little things

Yeah, so today, I’m pulling down boatloads of JSON in this application I’m working on (mainly lookup-data-ish-data), and obviously if I’m going to use some of that data to do lookups, I need to wait until they’re all downloaded.  So, instead of some cheese eventing hack, I took advantage of the the little gem known as jQuery.when

(fyi, sorry for the crappy code-formatting below.  some day, i hope to take 15 minutes to figure out why either Live Writer or this crappy “Code” plugin suck so bad).

So, once my little lookup playloads were down, I was able to use it, nice-and-clean.  So, here’s where I slam down 4 ajax calls:

var ajaxSmackDown= function () {
     var promises = [];
     promises.push(detailsUtility.ajax(first ajax call here);
     promises.push(detailsUtility.ajax(first ajax call here);     
     promises.push(detailsUtility.ajax(first ajax call here);     
// (call as many as you want here…) return promises;
};

and here, we wait *when* to do our other stuff until they’re all done:

var promises = ajaxSmackDown();
$.when.apply($, promises).then(function () {
     // Do what you needed to wait on here
, function (e) {
     global.exceptionHandler(e);
});

Leave a comment