如何从 executeQueryAsync 获取 return 值?

How do I get the return value from executeQueryAsync?

我不知道如何从下面的方法中获取 return 值。我正在将项目添加到数组中。那很好用。我就是无法从函数中获取数组 returned。

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?

            });            
    }

这是不可能的,因为您不能 return 从同步方法中的异步调用。但是你可以通过传递一个回调函数来得到你想要的。

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.
});