I am trying to write some nested ajax calls with the help of function and when. But currently, my then function is not working as expected. I want to call then function when all Ajax calls are done including the nested ones. I want to call then function when
this.getDescendants(resourceId[1],resourceData.limit+resourceData.offset);
is also completed for all the main ajax calls. Currently, then is completing before the nested ajax calls are completing.
getUserInfo: function(){
$.ajax({
type: "GET",
contentType: "application/json",
url: UserURL,
context: this,
beforeSend: function (xhr) {
$('#fade-wrapper').fadeIn();
xhr.setRequestHeader('Authorization', "Basic "+this._basicCred);
},
success: function(resourceData) {
if(resourceData.resources != undefined && resourceData.resources.length > 0){
var deferreds = [];
for (var i=0; i < resourceData.resources.length; ++i){
var deferred = this.getDescendants(resourceData.resources[i],0);
deferreds.push(deferred);
}
$.when.apply($, deferreds).then(function() {
var currentContext = this[0];
console.log(currentContext);
console.log("Then called.");
});
} else {
alert("No visible resource has been found.");
}
}.bind(this),
error: function(xhr, status, err) {
console.error( status, err.toString());
$('#fade-wrapper').fadeOut();
alert("Error has occurred, please contact administrator in case the problem persists.");
return null;
}.bind(this)
});
},
getDescendants: function(resId,offset){
return $.ajax({
type: "GET",
contentType: "application/json",
data: {"resId":resId},
url: DesedentURL+"?limit=10&offset="+offset,
context: this,
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', "Basic "+this._basicCred);
},
success: function(resourceData, textStatus, xhr) {
if(this._resResults == undefined){
this._resResults = [];
}
this._resResults.push(resourceData);
console.log("resourceData");
console.log(resourceData);
if(resourceData.totalResults > (resourceData.limit+resourceData.offset) ){
var resourceId = resourceData.links[0].href.match("resources/(.*)/descendants");
console.log(resourceId);
this.getDescendants(resourceId[1],resourceData.limit+resourceData.offset);
}
}.bind(this),
error: function(xhr, status, err) {
console.error( status, err.toString());
$('#fade-wrapper').fadeOut();
alert("Error has occurred, please contact administrator in case the problem persists.");
return null;
}.bind(this)
});
}