2

I'm making concurrent AJAX requests but having an issue while trying to wait till all the calls have returned, console.log inside done() is showing result as an empty array. $.when isn't waiting for the requests to finish.

 var result = []
  var promise = []
  for (i=0;i < array.length;i++)
  {
    _url = "http://example.com"
      var req = $.ajax(
        {
          type: "GET",
          url: _url,
          success: function(request) { result.push(request)         
          } ,
          error: function(request) {  result.push("ERROR BROTHA")              
        }
        });
      promise.push(req)
  }

  $.when(promise).done(function(){
    console.log(result);
  });
Yury Tarabanko
  • 44,270
  • 9
  • 84
  • 98
Pratyay
  • 2,176
  • 1
  • 15
  • 14

1 Answers1

2

You need to spread array. Docs.

$.when.apply($, promise).done(...);

From docs

jQuery.when( deferreds )

deferreds Zero or more Deferred objects, or plain JavaScript objects.

Yury Tarabanko
  • 44,270
  • 9
  • 84
  • 98