Search code examples
javascriptsharepoint-jsom

How do I get the return value from executeQueryAsync?


I cannot work out how to get a return value from the method below. I am adding items to an array. That works fine. I just cannot get the array returned from the function.

var termList = loadTerms(termSetId);

function loadTerms(termSetId) {

        var termList = [];
        var taxSession = SP.Taxonomy.TaxonomySession.getTaxonomySession(clientContext);
        var termStore = taxSession.getDefaultSiteCollectionTermStore();
        var termSet = termStore.getTermSet(termSetId);
        var terms = termSet.getAllTerms();

        clientContext.load(terms, 'Include(Name)');

        clientContext.executeQueryAsync(
            function () {                    

                for (var i = 0; i < terms.get_count(); i++) {

                    var term = terms.getItemAtIndex(i);
                    termList.push(term);
                    console.log(String.format('12 Term : {0}', term.get_name()));
                }

                // At this point TermList has the values I need. How do I return it to the caller?

            });            
    }

Solution

  • It is impossible as you can not return from an asynchronous call inside a synchronous method. But you can get what you want by passing a callback function.

    var termList = loadTerms(termSetId);
    
    function loadTerms(termSetId, callback) {
    
      var termList = [];
      var taxSession = SP.Taxonomy.TaxonomySession.getTaxonomySession(clientContext);
      var termStore = taxSession.getDefaultSiteCollectionTermStore();
      var termSet = termStore.getTermSet(termSetId);
      var terms = termSet.getAllTerms();
    
      clientContext.load(terms, 'Include(Name)');
    
      clientContext.executeQueryAsync(
        function() {
    
          for (var i = 0; i < terms.get_count(); i++) {
    
            var term = terms.getItemAtIndex(i);
            termList.push(term);
            console.log(String.format('12 Term : {0}', term.get_name()));
          }
    
          callback(termList); // callback here
    
        });
    }
    
    loadTerms("termSetId", function(returnedValue) {
      console.log(returnedValue); //You get the value here.
    });