"Utilizing SharePoint's JSOM to retrieve taxonomy in a recursive manner

I am facing an issue with retrieving a tree of terms recursively from a term group using JSOM / JavaScript.

The challenge lies in the fact that all values are being fetched recursively, but the order is completely incorrect.

 function recurseTerms(currentTerm, loops){
loops++;
var terms = currentTerm.get_terms(); 
context.load(terms); 
context.executeQueryAsync( 
    function () {
        var termsEnum = terms.getEnumerator();

        while (termsEnum.moveNext()) {
            var newCurrentTerm = termsEnum.get_current();
            termstext += newCurrentTerm.get_name() + "<br>";

            //Check if term has child terms.
            if (newCurrentTerm.get_termsCount() > 0) {
                recurseTerms(newCurrentTerm, loops);
            }
        }
        document.getElementById("resultsDiv").innerHTML = termstext;
 },
 function () {

//failure to load terms

});

Therefore, when I call the function recurseTerms with the Term-object as the first parameter (root) and 0 for loops (solely for formatting), my hierarchy of terms appears as follows:

Level 1
--Level 1a
--Level 1b
Level 2
Level 3
--Level 3a
----Level 3a
------Level 3a1
------Level 3a2
--------Leve...

However, the actual output generated by the function (termstext) reads:

Level 1
Level 2
Level 3
Level 1a
Level 1b
... 

This discrepancy suggests that the function fails to recognize child terms underneath 'Level 1' and struggles to recurse accordingly.

Although I have identified the problem, finding a solution has proven challenging :( Any guidance on the correct approach would be greatly appreciated!

Answer №1

After a considerable amount of time, I successfully resolved this issue by implementing JavaScript promises. Once level 1 is obtained, we are able to execute the function again and continue the process.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The unexpected ) token in Node.js is causing an error when evaluating a function

Storing and retrieving a function from the database using node.js is causing some unexpected behavior. When I attempt to log the column containing the function, this is the output: (function(settings){var options = {host: 'somehost.com',path: & ...

Unable to automatically close browser window after test execution with NightwatchJS

I recently executed my first Nightwatch test, as indicated in the code below. The test ran smoothly - Selenium successfully entered 'wiki' into Google and submitted the form, resulting in a passing test. However, I am now looking to automate the ...

Having trouble with the Vuejs validation code not functioning correctly?

I need help with a JavaScript function that posts objects to the backend only if all items are numbers. Here is the code snippet I'm working with: var MyApp = new Vue({ el: '#my_element', data: { errors: [], ...

Insert an array inside another array using JavaScript (jQuery)

I've been attempting to use the push() method within a loop to construct a data structure as shown below: var locations2 = [ ['User', position.coords.latitude, position.coords.longitude, 1], ['Bondi Beach', -33.890542, 151 ...

Unable to bring in the Firebase Firestore Colletion

When working on my next app, I encountered an error while trying to call a Firestore Collection. The specific error message that appeared when I ran the app was: FirebaseError: Firebase: Firebase App named '[DEFAULT]' already exists (app/duplicat ...

Issue related to the structure of a redis reply

Currently, I am facing the challenge of reformatting an incoming string from redis before sending it to the client. The original format looks like this... "[{'user_id': 1, 'username': 'one', 'coins_won': 10}, {& ...

The expansion animation for the Nextjs/React accordion box did not work as expected when utilizing tailwindcss

I am currently working on creating an animation for a collapsible box (accordion). My goal is to have the child component initially hidden with display:none. When I hover over the parent component, the child should be revealed and the dimensions of the pa ...

Order the results by a predicate chosen by the user and a predefined secondary attribute

Trying to organize a table of results by a user selected criterion and then by a predefined secondary one. For instance, the ng-repeat setup looks like this: <tr ng-repeat="line in model.resultList | orderBy:['-predicate', 'secondary_va ...

After the state loads in Ui-router, how can I execute a function?

Transitioning from jQuery to Angular, I am struggling with ui-router and states. In jQuery, I can make an AJAX call and then run another function on success. How can this be achieved in Angular? For instance, consider the code snippet below: var ivApp = ...

Learn how to easily insert a marker on a map using leaflet js in vue 3 with just a simple click

Hey everyone! I need some help with a challenge I'm facing. I can't seem to get click coordinates to create a new Marker on my map. Check out the image here And another image here ...

The "smiley" character added to the information during an Ajax call

Encountering an unusual issue. A colon (:) character is being appended to the JSON data sent to the server via AJAX request. https://example.com/image1.png The colon character seems to appear after sending the JSON, but it does not show up when inspectin ...

Properly handling the use of single and double quotation marks in variable declarations within a JavaScript file

I have a search box where users can enter their search text. For example, they can type book, 'book', or "book". The value entered in the search box is then assigned to a variable in the JavaScript file. var searchTerm = "${searchTerm}"; <br/ ...

The issue with the `this` keyword in a jquery event handler when using Typescript

Here is my TypeScript code snippet. class something { createSomething(): JQuery { let result = $('<div>'); $('<input>').on('change paste keyup', () => { this.myProperty = $(this) ...

Exploring the benefits of utilizing ChartJs within a VueJs component

I'm currently working on using Chartjs to create and control a chart within a Vue component. I'm feeling a bit lost as to where exactly in the script tags I should initialize the chart instance var myChart = new Chart(ctx, {...}); after importing ...

What might be causing my lightbox image to fail to load when I click on it?

Whenever I click on the image, the lightbox loads but the actual image fails to load, leaving a blank white box instead. Despite following a tutorial on YouTube that showed me how to create a lightbox step by step, I can't figure out what went wrong. ...

Monitoring the sharing of content on social media networks, rather than tracking individual

After setting up a hidden page on my site and configuring buttons to test pushing data to the dataLayer, I have ensured that my Google Tag Manager (gtm) is functioning properly. I recently tracked a Google +1 button click successfully, confirming that my c ...

Creating dynamic routes in express.js with fixed components

I'm exploring how to create a route in express that captures URLs like this: /events/0.json Here's what I've attempted so far (but it's not working as expected): router.put('/events.json/:id.json', isLogged, events.update) ...

Having trouble launching the freshly developed Angular app

I'm encountering an issue with my newly created app - I can't seem to launch it. Error: The loader “C:/C#/Angular/my-app/src/app/app.component.css” is not providing a string as expected. https://i.sstatic.net/6Xjwd.png https://i.sstatic.ne ...

What is the best method for concealing a Link React component entirely?

I have implemented a sidebar feature with settings that allow the user to toggle the visibility of desired sections. Here is an example of how this component appears: <List> {section.elements.map((subsection) => ( <ListItem key={subsection ...

Need help addressing a sliding page issue in my Upwork clone script using JavaScript

For those familiar with Upwork's UI, you may have noticed a small feature I implemented. When a user clicks on a freelance job offer, another page opens from the left side using transform: translate(120%) to transform: translate(0). The issue arises ...