I'm trying to get the terms from sharepoint online and put them into a select tag using JavaScript.
My terms are set up like I have main categories and each of them have sub categories.
For example
-Entertainment
---TV
---Games
---Music
So I loop through the main categories and get the id for each of them. Then inside that loop I try to get the sub categories for each main id.
The result is that it only succeed to get the sub categories from the last main id and fails on first. By the order on my console.log messages in console my guess is that it has to do with the async query. But how can I work my way around this?
function loadTerms() {
var appContext = new SP.ClientContext.get_current();
var taxSession = SP.Taxonomy.TaxonomySession.getTaxonomySession(appContext);
//Term Store under which to create the term.
var termStore = taxSession.getDefaultSiteCollectionTermStore();
//Pass ID of the Meetings Term Set
var termSet = termStore.getTermSet("275d8d26-a608-4fdd-b9bf-1e3ab3c350c4");
var terms = termSet.get_terms();
appContext.load(terms);
appContext.executeQueryAsync(function () {
var termEnumerator = terms.getEnumerator();
while (termEnumerator.moveNext()) {
let currentTerm = termEnumerator.get_current();
console.log(currentTerm.get_name());
console.log(currentTerm.get_id());
var termSetParent = termStore.getTerm(currentTerm.get_id());
var termSetGroupTerms = termSetParent.get_terms();
appContext.load(termSetGroupTerms);
appContext.executeQueryAsync(function () {
var termGroupEnum = termSetGroupTerms.getEnumerator();
while (termGroupEnum.moveNext()) {
console.log(termGroupEnum.get_current().get_name());
}
}, function (sender, args) {
console.log(args.get_message());
});
}
}, function (sender, args) {
console.log(args.get_message());
});
}