I recently ran into a situation where I had multiple AJAX calls completing and needed to perform some logic when they ALL finish. I can never seem to remember how to do this when I need it so, here’s a blog post, even if just for my benefit.
In my situation, I was simply hiding a load icon, and yes, I did not have a way to combine the AJAX calls which would have been more ideal performance wise. For this example we will be using JQuery for the AJAX calls and promise tooling.
A JQuery AJAX call returns a promise. The basic work flow is to push each promise returned by an AJAX call into an array. We then iterate through the array firing each AJAX call and wait for them to complete. Once they ALL complete, we can kick off our final logic. Here’s the code:
Define the array for holding all of our promises:
Load some AJAX calls into our array:
Iterate through, running each AJAX call. When they all complete, run our completion logic:
That’s it, feel free to add comments below and let me know if you have any questions or cool insights on improving or expanding!