0

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) {
   myDoElement.html(topMenu);
});

function GetTerms(){
  var dfd = $.Deferred();
  var arr1 = [];
  //some variables and code here
   clientCtx.load(terms);
   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
               arr1.push(childItemsHtml);
          });             
       }
      //push closing html elements into arr1
      dfd.resolve(arr1.join(''));
   }),
   Function.createDelegate(this, function (sender, args) {
      dfd.reject(args.get_message());
   }));
   return dfd.promise();
}

function GetSubTerms(parent) {
    var dfdChild = $.Deferred();
    var arr2 = [];
    var childs = parent.get_terms();
    clientCtx.load(childs);
    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
          dfdChild.resolve(arr1.join(''));
     }),
     Function.createDelegate(this, function (sender, args) {
         dfdChild.reject(args.get_message());
     }));
     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.

0

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.