Reputation: 512
I have a set of files a.json, b.json, c.json, etc., and I want to load the data contained therein to a single data structure in JavaScript. However, the last line of the following code always returns 0 instead of 3 which I expect. What am I doing wrong?
files = ["a", "b", "c"];
var dataset = [];
function getObject(file) {
return $.getJSON(file).then(function (data) {
return data;
});
}
for (i = 0; i < files.length; i++) {
getObject(files[i] + ".json").done(function (data) {
dataset.push(data);
});
}
alert(dataset.length)
Upvotes: 1
Views: 78
Reputation: 12857
You could handle it in the done
method:
var doneCount = 0;
for (i = 0; i < files.length; i++) {
getObject(files[i] + ".json").done(function (data) {
dataset.push(data);
if ( ++doneCount == files.length ){
alert(dataset.length);
}
});
}
Upvotes: 1
Reputation: 92274
First, if run your alert
immediately after the calls to $.ajax
return, the data isn't available and your variable hasn't been set. You have to wait until done is called (which is long after the method call to $.ajax
returns, since it's asynchronous). How do I return the response from an asynchronous call?
Second, to synchronize requests, you can use $.when
so you're notified when all requests resolve. Wait until all jQuery Ajax requests are done?
var files = ["a", "b", "c"];
var dataset = [];
var requests = [];
for (i = 0; i < files.length; i++) {
requests.push($.getJSON(files[i] + ".json") );
}
// $.when may not take the requests as an array, in that case use
// $.when.apply($, requests).done();
$.when(requests).done(function() {
for (var i=0; i < arguments.length; i++) {
dataset.push(arguments[i]);
}
alert('All three received, dataset length is ' + dataset.length)
})
Upvotes: 1