Lasagna Lasagna - 6 months ago 25
jQuery Question

Why does the .done() method finish executing before the $getJSON calls finish executing?

I have been having an issue where one of my methods is executing before my getJSON calls are finished executing. This method needs the data from the calls before executing itself.

I have looked up a few things such as "deferred calls or .done(), but my main issue is that my nested getJSON calls are variable. This means from my first file I get a number and with that number I create a loop and then do multiple getJSON calls based on that number. I cannot attach a .done() because I have to do it multiple times, and a deferred call wont work for the same reason. For some reason the first .done() doesn't wait until the inner getJSON calls finish before executing... Is that supposed to happen?

$.getJSON(file, function(d)
{

for(var i = 0; i < d.name.length; i++)
{
files[i] = d.name[i];



fileName = "/"+files[i];

$.getJSON(fileName+'.PNG', function(data)
{


json[i] = data;
});
}
})

.done(function()
{
makeUL(plan); //doesn't work but needs the data from json[i] in order to continue.
})

.fail(function( jqxhr, textStatus, error )
{
var err = textStatus + ', ' + error;
console.log( "Request Failed: " + err);
alert("failed");
});


Anyone have an idea how I can do this?

Thanks all :)

Answer

You can try to use $.when() which can be used for all the promises to complete

$.getJSON(file, function (d) {
    var requests = $.map(d.name, function (value, i) {
        files[i] = value;
        var fileName = "/" + value;
        return $.getJSON(fileName + '.PEV', function (data) {
            json[i] = data;
        });
    });

    $.when.apply($, requests).done(function () {
        makeUL(plan);
    });
}).fail(function (jqxhr, textStatus, error) {
    var err = textStatus + ', ' + error;
    console.log("Request Failed: " + err);
    alert("failed");
});