Как получить возвращаемое значение от executeQueryAsync?

Я не могу понять, как получить возвращаемое значение из метода ниже. Я добавляю элементы в массив. Это отлично работает. Я просто не могу получить массив, возвращенный из функции.

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?

            });            
    }

1 ответ

Решение

Это невозможно, поскольку вы не можете вернуться из асинхронного вызова внутри синхронного метода. Но вы можете получить то, что вы хотите, передав функцию обратного вызова.

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

Другие вопросы по тегам