I'm trying to make 2x Ajax calls at the same time (async) with jQuery, like the following:
function displayAccount() {
$.when(doGet("accounts/1", null),
doGet("orders/1", null))
.done(displayAccountSuccess);
}
function displayAccountSuccess(accountJson, ordersJson) {
console.Info(accountJson);
console.Info(ordersJson);
}
When I do this, the displayAccountSuccess
is called BEFORE the 2x doGet
's are called/handled. Of course, the values of the two method arguments are undefined
.
So obviously my doGet
isn't returning a promise :(
For that method...
function doGet(endpoint, queryString)
{
var url = ApiWebsite + "/" + endpoint;
if (queryString)
{
url += "?" + queryString;
}
var authorizationHeader = isAuthenticated()
? "bearer " + localStorage.getItem(LocalStorageJwt)
: "";
$.ajax({
url: url,
headers: {
authorization: authorizationHeader
}
})
.done(function(json)
{
return json;
})
.fail(function(data1, data2){
displayError("fail");
}).promise();
}
Ok - now this is what is interesting :) the ajajx.done
method DOES have the correct json response in there! So I -thought- I was returning that json data back to the caller.
Now, if i change the code from:
$.ajax(....
to
return $.ajax(....
the when.done(..)
function is delayed and only called after the 2x ajax calls are completed! Yay! ..but ... the VALUE of this data is an array of 3 items .. the data, successTest, jqXHR
:( Sure, I can just get the json value from array slot 0 (accountJson[0]
) but this means I'm not understanding something pretty basic here :(
I'm hoping that my done()
method will accept 2x json objects only, not the full SUCCESS (or failure) array.
I hope this makes sense :blush: