Besser mehrere Rückrufe kombinieren?

Ich muss eine asynchrone Funktion (mit Schleife) für mehrere Werte aufrufen und auf diese Ergebnisse warten. Im Moment benutze ich den folgenden Code:

(function(){
    var when_done = function(r){ alert("Completed. Sum of lengths is: [" + r + "]"); }; // call when ready

    var datain = ['google','facebook','youtube','twitter']; // the data to be parsed
    var response = {pending:0, fordone:false, data:0}; // control object, "data" holds summed response lengths
        response.cb = function(){ 
            // if there are pending requests, or the loop isn't ready yet do nothing
            if(response.pending||!response.fordone) return; 
            // otherwise alert.
            return when_done.call(null,response.data); 
        }

    for(var i=0; i<datain; i++)(function(i){
        response.pending++; // increment pending requests count
        $.ajax({url:'http://www.'+datain[i]+'.com', complete:function(r){
            response.data+= (r.responseText.length);
            response.pending--; // decrement pending requests count
            response.cb(); // call the callback
        }});
    }(i));

    response.fordone = true; // mark the loop as done
    response.cb(); // call the callback
}()); 

Das ist nicht alles sehr elegant, aber es macht den Job. Gibt es einen besseren Weg, es zu tun? Vielleicht ein Wrapper?

Antworten auf die Frage(2)

Ihre Antwort auf die Frage