In the process of developing a method for creating markup to be used in a web app's off-canvas navigation. One of the challenges I am facing is making an asynchronous callback to another service that provides children nodes for the parent menu node (refer to code snippet below):
function GenerateMarkup(Terms, n) {
var termsEnum = Terms.getEnumerator();
var html = "<ul>";
// Handling top level terms
while (termsEnum.moveNext()) {
var currentTerm = termsEnum.get_current();
html += "<li>"
if (currentTerm.get_termsCount() > 0) {
var childcall = function() {
var deferred = $.Deferred();
html += "<a href=\"#\">" + currentTerm.get_name() + "<br><span>" + currentTerm.get_description() + "</span></a>";
SPTermStore.GetTermsFromTermSet(currentTerm).then(function(termSet) {
if (typeof termSet !== undefined) {
deferred.resolve(GenerateMarkup(termSet, n++));
}
else
deferred.reject("something bad happened");
});
return deferred.promise();
};
$.when(childcall()).done(function(markup) {
html += markup;
});
} // end if
else
html += "<a href=\"#\">" + currentTerm.get_name() + "</a>";
html += "</li>"
} // end while
html += "</ul>";
console.log("GenerateMarkup (" + n + "): " + html);
return html;
} // end function
The issue I am encountering is related to the order in which the markup is generated; instead of completing the recursive call to GenerateMarkup synchronously, I need to wait for the returned promise so that I can append the HTML accordingly. The objective is to process the child nodes as the iteration progresses through the parent nodes.
Upon inspecting the console log output, the problem becomes clear. The first listed markup represents what is actually returned to the page, rather than a combination of the items below:
GenerateMarkup (0): <ul><li><a href="#">About<br><span>Our Company</span></a></li><li><a href="#">Portfolio<br><span>Our Properties</span></a></li><li><a href="#">Corporate Responsibility<br><span>Our Commitment</span></a></li></ul>
GenerateMarkup (0): <ul><li><a href="#">Careers</a></li><li><a href="#">Core Values</a></li><li><a href="#">Governance</a></li><li><a href="#">History</a></li></ul>
GenerateMarkup (1): <ul><li><a href="#">Core Market Strategy</a></li><li><a href="#">Our Properties</a></li></ul>
GenerateMarkup (2): <ul><li><a href="#">Community Involvement</a></li><li><a href="#">CSR Report</a></li><li><a href="#">Diversity</a></li><li><a href="#">Sustainability</a></li></ul>
I would greatly appreciate any assistance with this matter.