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)
3

2 Answers 2

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)
})
Sign up to request clarification or add additional context in comments.

Comments

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

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.