Sunday, 28 May 2017

How can I build and return a folder tree in Javascript?

Due to the async nature of Javascript I am having issues returning the finished document tree so I can then process it. In this function I call the api to retrieve all the children of a child and then recurse again through the function. When all the recursions are finished and the folder tree has been built there is currently no way to return the tree.

function buildTree(documentTree) {

    let childrenNum = documentTree.relationships.children.length;
    //traverse children of the tree
    for (let i = 0; i < childrenNum; i++) {

        let itemGroupId = documentTree.relationships.children[i].attributes.groupId;
        //if folder then get children
        if (documentTree.relationships.children[i].attributes.isFolder) {
            api.retrieveFolderTreeJson(itemGroupId, (err, json) => {
                        if (err) {
                            logger.error('Error occured fetching folder tree node with id %d ' + __filename, itemId);
                            return;
                        }
                        let childTree = JSON.parse(json).data;

                        //Add nodes children
                        documentTree.relationships.children[i].children = childTree.relationships.children;

            //repeat process to go through whole tree
           buildTree(childTree);
    });
        }

    }
}



via Paul Beliavskis

No comments:

Post a Comment