1

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)
dust
  • 502
  • 6
  • 19
  • 2
    Look into asynchronicity and the concept of promises/deferred objects. You're alerting before the loads have completed because the load actions as asynchronous. The code does not pause to enact them. – Mitya May 09 '14 at 18:42
  • 1
    [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – Jonathan Lonowski May 09 '14 at 18:43
  • 1
    [Wait until all jquery ajax request are done?](http://stackoverflow.com/questions/3709597/wait-until-all-jquery-ajax-request-are-done) – Jonathan Lonowski May 09 '14 at 18:53

2 Answers2

1

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);
        }
    });

}
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
T McKeown
  • 12,971
  • 1
  • 25
  • 32
1

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)
})
Community
  • 1
  • 1
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217