Following is a working solution for a single xml ajax to retrieve category list, then individual ajax calls for each category. This was developed in response to a question on SO.
Solution creates one deffered for the category ajax call, and array of deffereds for the items ajax calls. Bottom of code nests $when(itemsCallsArray)
inside $.when( catgoryCall)
Categories should stay in order of xml but looking for any improvements that could be used to keep the items calls in order.
/* store all ajax content in object*/
var content = {};
function parseContent(content) {
$.each(content, function() {
$('body').append('<br><br>' + this.a + '<br>' + this.b.join('<br>'));
})
}
/* array to store nested ajax promises */
var deferreds_b = [];
/* A promise and ajax*/
var xml_A = $.post("/echo/xml/", {
xml: a
}, function(returnedXML) {
var $el_A = $(returnedXML).find("ElementA");
var total_A = $el_A.length;
$el_A.each(function(counter) {
var countA = counter;
var name_of_Attribute_of_Element_A = $(this).attr("name");
/* create EL A object , store EL A content, create array to push B content to */
content[countA] = {
a: countA + ". " + name_of_Attribute_of_Element_A,
b: []
}
var xml_B = $.post("/echo/xml/", {
xml: b
}, function(returnedXML) {
var $el_B = $(returnedXML).find("ElementB");
var total_B = $el_B.length;
$el_B.each(function(idx) {
var name_of_Attribute_of_Element_B = $(this).attr("name");
content[countA].b.push(countA + ". " + name_of_Attribute_of_Element_B);
});
});
/* push B promise to array*/
deferreds_b.push(xml_B);
});
});
$.when(xml_A).done(function() {
/* when A is done , wait for B to be done*/
$.when.apply(null, deferreds_b).done(function() {
parseContent(content);
$("body").append("<p>All done!</p>");
});
})