AJAX - Wailt until all ajax is complete to take action

by bizamajig

HTML

<!--
SEE:      http://stackoverflow.com/questions/5627284/pass-in-an-array-of-deferreds-to-when
SEE ALSO: http://stackoverflow.com/questions/23207163/jquerys-when-apply-and-wrapped-async-functions
-->
<a href="#">Click me!</a>
<div class="progress"></div>

JavaScript

function GetSomeDeferredStuff() {
    var promises = [];
    var i = 1;
    for (i = 1; i <= 10; i++) {
        var count = i;
        promises.push(
/*
        $.post('/echo/html/', {
            html: "<p>Task #" + count + " complete.",
            delay: count
        }).success(function(data) {
            $("div").append(data);
        }));
*/
//          Push expects an expression here, instead of return $.ajax(), so no return statement
            $.ajax({
                type: 										'POST',
                url: 										'/echo/html/',
                cache: 										false,
                data:                                       {counter:i}
            }).done( function( response ) {
//              $("div").append( response );
                $("div.progress").append( "<p>Processing..." + count + "</p>" );
            })
        );
    }
    return promises;
}
$("a").click(function() {
    var deferreds = GetSomeDeferredStuff();
/*
$.when.apply($, promises).done(function() {
    // put code here that runs when all the ajax calls have completed
    // the results of all the ajax calls are in
    // arguments[0], arguments[1], etc...
}).notify(function() {
    // .notify is purely optional and only necessary if you want to be notified as
    // each async operation completes
    // This will get called as each async operation completes with whatever arguments
    // were passed to the success handler
}).fail(function() {
    // this will get called immediately if any of the async operations failed
    // the arguments are the same as the .done() function except that some may be empty
    // if they didn't complete before one of them failed
});
*/
//  $.when.apply(null, deferreds).done(function() { // null or $ as default context
    $.when.apply($, deferreds).done(function() { // null or $ as default context
        $("div.progress").append("<p>All done!</p>");
    });
});