views:

44

answers:

3

I wonder which is the best approach to trigger an event after several (unordered) ajax calls finished.

To make it a bit clearer, I would like to call a Method doSomethingGreat() which triggers several ajax calls, the order in which those succeed ins unnecessary. I just want to trigger an event 'SomethingGreatFinished' when all of those calls succeeded. I also don't want to chain these calls, because that would be lacking performance and would be totally against the idea of asynchronous programming.

I wonder if a.) there is a common pattern for that, b.) this can be done with the Reactive Extensions for JavaScript (RxJs) or c.) with native jquery features.

Any help is appreciated!

A: 

If you know how many calls are being made, then set a variable to that number, and decrement it each time an AJAX completion event occurs. When the variable reaches zero, 'SomethingGreat' has happened.

belugabob
That's what I do by now, but I thought there must be a nicer way to accomplish it. Maybe with the Reactive Extensions for JS?
Christoph
+1  A: 

You should have a look at .ajaxStop().

However, that callback will fire on every single ajax request that completes. So in order to know when your last request completes, you need either to invoke .ajaxStart() aswell, or you need to iterate a global variable for each request you fire and decrement it on .ajaxStop(). If that variable reaches zero, all your request have completed.

jAndy
+1  A: 

RxJS will allow you to do this using the ForkJoin operator, this operator takes N observables with a value and creates one observable that fires with an array when all N observables complete.

See Matthew Podwysocki's blog post about this operator: http://codebetter.com/blogs/matthew.podwysocki/archive/2010/04/23/introduction-to-the-reactive-extensions-for-javascript-going-parallel-with-forkjoin.aspx

Jeffrey van Gogh
I think that's exactly what I was looking for :-)
Christoph