AJAX callbacks when getting multiple XML files

In this example, I want to get two or more XML files using AJAX, then extract the content I need from them, and then store that data in an array outside of the AJAX call. I want to use the “dataExt” array to plot a google chart, but I am getting hung up implementing callbacks properly. I guess my brain just isn’t big enough yet!

Related

1 Comment

Digin DominicMay 15, 2015 at 2:02 pm

When you make an AJAX request, the call to $.ajax() returns immediately. It does not wait around for the content to come back over the network. In your example, the console.log() statements are being called before the callbacks have been completed.

What you want is a single callback that gets executed once all the data you need from your various requests has been fetched. To do this you need some sort of synchronization between the various AJAX calls that you’re doing. jQuery alone doesn’t support this that well.

You can roll this yourself. However, this is a common enough design problem that whole libraries have been written to handle it.

Do some Googling on the Promise pattern. Once you’ve done that, have a look at the Q library, which is one of several implementations of the pattern. They have done most of the hard work of synchronizing multiple AJAX requests for you.

In this example, the xmlPromise() function creates a promise object for you based on the URL you want to fetch. This promise represents a unit of work that will be completed at some time in the future. When the AJAX call you create in the promise returns successfully, it calls the resolve() method which lets Q know that the promise has been fulfilled, and the data is ready for use.

Once the promises are constructed, we pass an array of them into Q.allSettled(), which actually fires off the requests. Because these requests are asynchronous, they are executed in parallel. Once all of the promises either resolved or been rejected, Q will call the function you pass into the then() method, and pass in the results of your AJAX calls.