Pratyay Pratyay - 5 months ago 15
jQuery Question

$.when promise object not working

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);
});

Answer

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.