I have a circumstance where I need to make several getJSON calls, and once all of the data is returned make a call to another function, like so (code simplified for example):
var data = {};
for (var i in a) {
$.getJSON(base_url+i, function(d) {
data[i] = d;
});
}
do_something(data);
Obviously this doesn’t work as I am making the call to do_something before the getJSON calls have returned any data.
My current approach to get around this is to make the calls synchronously, like so:
var data = {};
$.ajaxSetup({'async':false});
for (var i in funcs) {
$.getJSON(base_url+i, function(d) {
data[i] = d;
});
}
$.ajaxSetup({'async':true});
do_something(data);
My question is, is there a better way of doing this or am I best off making the calls synchronously as above?
As per link posted by Felix Kling to a similar question, the answer was to use deferred objects.
However, there is a further complication due to the use of
iin thegetJSONsuccess function. This would always be the value of the last iteration. See my other question for more details:jQuery Deferred – Variable scope in deferred getJSON success functions
Full solution: