I’m working on a project where inside a loop I need to make multiple JSON calls. As soon as I exit that loop I need to work with the results of all the calls I made. I’m having a hard time understanding how to make these calls in such a way that my order of operation works out. My code to work with the results always executes before the calls to the service have completed. I created a jsfiddle to demonstrate and am including the code here.
var sourceData = { "fooIndex": "foo",
"barIndex": "bar"
}
var destinationData = {};
for (var sourceIndex in sourceData) {
$.getJSON('http://echo.jsontest.com/' + sourceIndex + '/' + sourceData[sourceIndex] + '?callback=?', null, function (result) {
for (var resultIndex in result) {
alert("Adding " + resultIndex + " : " + result[resultIndex]);
destinationData[resultIndex] = result[resultIndex];
}
});
}
if (Object.keys(destinationData).length == 0) {
alert("Destination not yet populated");
}
else {
alert("Eureka! You did it!");
}
This looks like a job for jQuery Deferred Object, and my sidekick
$.when!Pass all the
$.getJSONcalls to$.when, and when they are all done, I’ll will call a function with all the results.Check this out:
NOTE: Since this is asynchronous,
destinationDatawon’t be available until the callback is triggered. Put any code that uses that inside the.done()callback.