I am trying to retrieve top navigation (terms and their sub terms) from MMS using JSOM and JQuery deferred. I need to have nested deferred because terms has sub terms. following is my code.

$.when(GetTerms()).done(function (topMenu) {

function GetTerms(){
  var dfd = $.Deferred();
  var arr1 = [];
  //some variables and code here
   clientCtx.executeQueryAsync(Function.createDelegate(this, function (sender, args) {
       var termsEnumerator = terms.getEnumerator();
       while (termsEnumerator.moveNext()) {
          // here adds som html using arr1.push("");
          var currentTerm = termsEnumerator.get_current();
          $.when(GetSubTerms(currentTerm)).done(function (childItemsHtml) {
              //adding sub terms
      //push closing html elements into arr1
   Function.createDelegate(this, function (sender, args) {
   return dfd.promise();

function GetSubTerms(parent) {
    var dfdChild = $.Deferred();
    var arr2 = [];
    var childs = parent.get_terms();
    clientCtx.executeQueryAsync(Function.createDelegate(this, function (sender, args) {
         //adding som html to arr1 using push
         var childsEnumerator = childs.getEnumerator();
         while (childsEnumerator.moveNext()) {
             var childTerm = childsEnumerator.get_current();
             //pushing elements into arr2
          //pushing closing html elements into arr2
     Function.createDelegate(this, function (sender, args) {
     return dfdChild.promise();

If I don't use GetSubTerms and want to only retrieve terms it works, but if I use GetSubTerms method to get sub terms, it only returns first top term. what is wrong with my code? thanks.


You need some logic to be recursive if there are more than one sub term and call your original function again if so. Not sure why you would need to use promises on the get sub terms function.

You could add an if statement like so within GetSubTerms();

if childTerm.get_termsCount() > 0 do more recursion here else break

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.