I wanna using $.deferred objects to handle my recursive function's requests.
but here I have a problem that
$.when wont wait for call1 success then do call2!
it wont send the returned data from call1 to call2 function!
note : only want to implement my ajax's with async:true;
thanks in advance!
m.mov
//*********************************************************************
var i = 3; // just run the queue 3 times
function getNode(node_object_array)
{
$.when(call1(node_object_array)).then(call2);
i--;
if(i >= 0)
getNode(next_level_childs);
}
function call1(node_object_array)
{
var root_array = new Array();
var d = new $.Deferred();
$.each(node_object_array , function(index , each_root_node) {
console.log("making request for"+each_root_node.node_guid );
$.ajax({
url: url ,
dataType: 'json',
success: function(json) {
root_array.push(getNodeData(json));
console.log("success request for"+each_root_node.node_guid );
},
});
});
d.resolve(root_array);
return d;
}
//****** call2 which receive data from call1 and call some $.ajax's ****
function call2(data)
{
var next_level_childs = new Array();
var d = new $.Deferred();
$.each(data , function(index , each_root_node) {
$.each(each_root_node.childs , function(index , each_root_node_child) {
console.log("making request for "+each_root_node_child );
$.ajax({
url: url ,
dataType: 'json',
async : false,
success: function(json) {
console.log("success request for"+each_root_node_child );
next_level_childs.push(getNodeData(json));
}
});
});
});
d.resolve(next_level_childs);
return d;
}
If you resolve the Deferred before your ajax call completes, then $.when will consider it finished and will call the next function (call2). What you need to do is resolve it on the success/fail of your ajax call inside call1.
Edit: You actually need to combine all the promises from your ajax calls so you only resolve the deferred after all of them have completed. I only just noticed the $.each call.