I think deferred
is what you are looking for:
http://api.jquery.com/category/deferred-object/
it looks like this:
$.when(some_promise).then(some_callback)
And you can have:
$.when(some_promise, another_promise).then(some_callback)
In this case, some_callback
will be called only when some_promise
and another_promise
were allowed.
deferred
basically just adds an abstraction layer to your asynchronous functions, making it easy to express dependencies. I assume your example will look like this:
// simple pubsub example var pubsub=(function() { var callbacksObj={}; return function(id){ if(!id) throw 'callbacks requires an id'; return some_assynchrnous_function(id); // like $.ajax }; })(); function fn1(){ console.log('fn1'); }; function fn2(){ console.log('fn2'); }; function fn3(){ console.log('fn3'); }; // subscribing var foo = pubusb('foo'); // should return a deferred/promise var bar = pubsub('bar'); $.when(foo).then(fn1); $.when(bar).then(fn2); $.when(foo, bar).then(fn3);
I'm not quite sure if this is correct for jQuery, but you get the idea. I did not find the jQuery API to make a lot of sense to me, so I wrote my own: 3
Itβs useful for me to be able to make βemptyβ deferred objects, and then attach the done
handler to it, and then transfer the deferred object to something that ultimately leads to its resolution. I'm not sure jQuery can do this.
At first, this may seem like a bit of a challenge, but if you can wrap your head around yourself, you can get so much value out of it. The dependencies are large, but the overview is also good, you can add several done
handlers at several levels, one handler can process the actual data, one handler may just be interested when the handler ends so you can show the loading bar, etc.