Recently I asked about how I could trigger a variable number of jquery get() requests and I received this code as a really efficient working solution:
var d = new $.Deferred();
var promise = d.promise();
var results = [];
for (var i = 0; i < 5; i++) {
    (function(i) {
        promise = promise.then(function() {
            return $.ajax('/echo/json/', {
                data: {
                    json: JSON.stringify({foo: i})
                }
            }).done(function(data) {
                results[i] = data;
            });
        });
    }(i));
}
promise.done(function() {
    console.log(results);
});
d.resolve(); 
I'm looking for an explanation of how exactly this works with the multiple done()s attached to each promise.then(), and then the final done() attached to the promise itself. Is it that a promise (from what I understand is a special type of sort of deferred itself) can have a done, then the deferred itself can also have a done? If it weren't in a loop, what would this syntax look like for, say, three ajax requests in a row? Just trying to get my head around it. Thanks!
 
     
     
    