As you're probably aware, xhr.get
happens asynchronously, meaning the code will continue to execute and note wait for it to finish. This is why the order is unpredictable.
Fortunately, this is not a new problem and can be solved using an array of Promises. A Promise
interface basically has a handler that will be fired when asynchronous results are returned, whether the call is successful or not. In your case, since you have an array of Promises that you need to handle at once, you can use a function called all
.
all
(in the case of dojo/promise/all) accepts an array of Promises as input, and executes when all of them have results returned. This means you can use all
with a Promise
for each of your calls to wait until they're all finished, and then process them. I haven't used dojo/_base/xhr
, but I can provide an example using dojo/request/xhr
which I'm sure is similar:
var promises = [];
for (var j=0; j<15; j++) {
var promise = xhr(url, {
handleAs: "json"
}).then({
function(data){
// process data, return results here
}
});
promises.push(promise);
}
all(promises).then(function(results) {
// process array of all results here
});
I've attached links to all
and Promise
so you can read about them more.