Reputation: 31
I have a single function making ajax calls to retrieve data. The issue I'm having is making nested ajax calls where one call depends on other and $.wait().then() is not really working. Is there any solution to my issue. Here is an example...
function _Ajax(params){
if(params == ''){
alert('no post params');
return;
}
var xdata;
$.ajax({
type: "POST",
url: "/xml/",
async: false,
data: params,
dataType: "xml",
success: function(xml){
xdata = xml;
},
error: function() {
alert("An error occurred while processing XML file. Params:" + objToString(params));
}
});
return xdata;
}
function A(a,b){
_Ajax({a:a,b:b});
}
function B(a,b,c){
_Ajax({a:a,b:b,c:c});
}
function C(a,b){
A(a,b);
B(a,b);
}
function D(a,b){
_Ajax({a:a,b:b});
}
function E(){
$.when(C(a,b)).then{function(){ D(a,b);});
}
I also tried to change async to true and it completely fails without returning any data. Thanks
Upvotes: 0
Views: 774
Reputation: 665536
$.when
doesn't magically wait for anything asynchronous, you need to pass promises to it - and for that, all of your functions need to actually return
them:
function _Ajax(params){
if(params == ''){
return $.Deferred().reject('no post params').promise();
}
return $.ajax({
type: "POST",
url: "/xml/",
data: params,
dataType: "xml"
}).catch(function() {
throw "An error occurred while processing XML file. Params:" + objToString(params));
});
}
function A(a,b){
return _Ajax({a:a,b:b});
}
function B(a,b,c){
return _Ajax({a:a,b:b,c:c});
}
function C(a,b){
return $.when(A(a,b), B(a,b));
}
function D(a,b){
return _Ajax({a:a,b:b});
}
function E(){
return C(a,b).then{function([xdata1], [xdata2]){ return D(a,b); });
}
Upvotes: 1