0

I've written this code in order to fetch items from multiple url's . I want to know when all of the $.get calls have been satisfied :

foo : function(arrIds){
    var arrJqxhr = [];
    var arrReturnedData = []
    for ( var i = 0, l = arrIds.length; i < l; i++ ) {
        var url = '/thing/' + arrIds[i].toString()
        arrJqxhr[i] = $.get(url)
            .done(function(data, textStatus, jqXHR) {
                arrReturnedData.push(data);
            })
    }

Apart from keeping count of how many times the .done has been called is there any better way ?

glaucon
  • 7,508
  • 9
  • 38
  • 59

1 Answers1

1

You can use $.when

 var arrReturnedData = [];
 var arrJqxhr = $.map(arrIds, function (id) {
     var url = '/thing/' + id.toString()
     return $.get(url)
         .done(function (data, textStatus, jqXHR) {
         arrReturnedData.push(data);
     })
 });

$.when.apply($, arrJqxhr).then(function(){
    //this will be called once all requests are successfully completed
    $.each(arguments, function(i, arr){
        arrReturnedData.push(arr[0])
    });
});
Roamer-1888
  • 18,902
  • 5
  • 31
  • 44
Arun P Johny
  • 376,738
  • 64
  • 519
  • 520