I have a little code segment like this:
var requestArray = [];
thingArray.forEach(function (thing) {
var uri = "https://server/_api/endpoint/things(" + thing.Id + ")";
requestArray.push($.ajax({
url: uri,
method: 'GET',
headers: {
accept: 'application/json;odata=verbose'
}
}));
});
$.when(requestArray).done(function(responseArray) {
responseArray.forEach(function(response) {
// response.responseJSON is undefined
});
});
and I realized I'm having the timing issue and responseJSON
is undefined because I'm passing an array of Deferreds to $.when()
, expecting it to be like Promise.all()
(which does take an array), but $.when()
just takes an unstructured "group" of Deferreds, so in my case $.when().done()
is resolving instantly because of the Array object passed in.
I tried to hack my way around it by doing
$.when(requestArray.forEach(function(req){ return req; })).done(function(responseArray) { })
(can't destructure like ...requestArray
because IE 11), but in that case responseArray
ends up being undefined
.
Looking back over the documentation for $.when()
, I see that all the examples have a known number of requests, and therefore can set up the done
function with a known number of parameters, like
$.when(req1, req2).done(function(resp1, resp2) { // etc })
So, how can I set up $.when().done()
to work if I have an unknown number of requests? My thingArray
in the example above is the result of a previous query, and could have any number of elements.