jQuery Deferred - waiting for multiple AJAX requests to finish [duplicate]

You can use .when(), and .apply() with multiple deferred. Extremely useful:

function updateAllNotes() {
    var getarray = [],
        i, len;

    for (i = 0, len = data.length; i < len; i += 1) {
        getarray.push(getNote(data[i].key));
    };

    $.when.apply($, getarray).done(function() {
        // do things that need to wait until ALL gets are done
    });
}

If you refer to jQuery.When doc, if one of your ajax call fails, fail master callback will be called even if all following ajax call haven't finished yet. In this case you are not sure that all your calls are finished.

If you want to wait for all your calls, no matter what the result is, you must use another Deferred like this :

$.when.apply($, $.map(data, function(i) {
    var dfd = $.Deferred();
    // you can add .done and .fail if you want to keep track of each results individualy
    getNote(i.key).always(function() { dfd.resolve(); });
    return dfd.promise();
});