0

I need to make n AJAX calls in a loop and store result in an array. When all requests are finished, and the array is full of returned JSON data, I want to loop through that to check it.

There are two problems here:

1) how do I make jqxhr available outside the $.each?

2) how does jqxhr know when the loop is finished to call complete? I only want to call the complete promise when the all AJAX calls within the loop finish.

    $.each(jsonFilesArray, function (i, jsonQuestID) {
        var jqxhr = $.getJSON("dialog/quest_"+jsonQuestID+".json", function(json) {
            vocabJSONArray.push(json);
        }).done(function () {
            log("done");
        }).fail(function () {
            log("error");
        }).always(function() {
            log("complete");
        });
    });

    jqxhr.complete(function () {
        //loop through vocabJSONArray
    });
user3871
  • 12,432
  • 33
  • 128
  • 268

1 Answers1

0

I suppose I can just wrap the requests in a closure to ensure that my loop values will always be what I expect, then run the loop within my always promise. Looking for a better solution though.

 $.each(jsonFilesArray, function (i, jsonQuestID) {
        (function (i, id) {
            $.getJSON("dialog/quest_" + id + ".json", function (json) {
                vocabJSONArray.push(json);
            }).always(function () {
                log("done");
                if (i === jsonFilesArray.length-1) {
                    //loop through vocabJSONArray
                }
            });
        })(i, jsonQuestID);
    });
user3871
  • 12,432
  • 33
  • 128
  • 268