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 handleABResponse(returnedXML, $el_A, countA) {
var name_of_Attribute_of_Element_A = $el_A.attr("name"),
$el_Bs = $(returnedXML).find("ElementB"),
results_b = [];
$el_Bs.each(function(index, el) {
var name_of_Attribute_of_Element_B = $(el).attr("name");
results_b.push (countA + ". " + name_of_Attribute_of_Element_B);
});
return {
a: countA + ". " + name_of_Attribute_of_Element_A,
b: results_b
}
}
/* Request As */
$.post("/echo/xml/", {
xml: a
}).pipe(function(returnedXML) {
/* process As */
/* array to store nested ajax promises */
var requests = [];
var $el_As = $(returnedXML).find("ElementA");
$el_As.each(function(countA) {
var $el_A = $(this);
/* push B promise to array*/
requests.push(
$.post("/echo/xml/", {
xml: b
})
.pipe(function bSuccess (response){
/* process A and Bs */
return handleABResponse(response, $el_A, countA);
})
);
});
/* return promise for all requests */
return $.when.apply( null, requests );
}).done(function() { //content[0], content[1],..
/* collect processed responses */
console.warn(this,arguments);
parseContent(arguments);
$("body").append("<p>All done!</p>");
});