JSFiddle - React, Tailwind, and code Playground
by Tomek
JavaScript
var a = '<root><ElementA name="A-1"></ElementA><ElementA name="A-2"></ElementA><ElementA name="A-3"></ElementA></root>';
var b = '<root><ElementB name="B-1"></ElementB><ElementB name="B-2"></ElementB><ElementB name="B-3"></ElementB></root>';
function parseContent(content) {
console.log('content',content);
$.each(content, function() {
$('body').append('<br><br>' + this.a + '<br>' + this.b.join('<br>'));
})
}
function handleBResponse(returnedXML, countA) {
var $el_B = $(returnedXML).find("ElementB"),
results_b = [];
return $el_B.map(function(index, el) {
var name_of_Attribute_of_Element_B = $(el).attr("name");
return (countA + ". " + name_of_Attribute_of_Element_B);
}).toArray();
}
/* A promise and ajax*/
$.post("/echo/xml/", {
xml: a
}).pipe(function(returnedXML) {
/* array to store nested ajax promises */
var requests = [];
/* store all ajax content in object*/
var content = {};
var $el_A = $(returnedXML).find("ElementA");
$el_A.each(function(countA) {
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
}
/* push B promise to array*/
requests.push($.post("/echo/xml/", {
xml: b
}));
});
requests.unshift( content );
return $.when.apply( null, requests );
}).done(function(content) { //,response1, response 2,...
console.warn(this,arguments);
for(var respNo = 0; respNo < arguments.length-1; respNo ++){
content[respNo].b = handleBResponse(arguments[respNo+1], respNo);
}
parseContent(content);
$("body").append("<p>All done!</p>");
});