My task involves creating a JSON output in tree structure from recursive async calls. The code I have developed for this purpose is detailed below:
$scope.processTree = function (mData, callback) {
_processTree.getWebCollection(mData.url).then(
function(_rdata){
// transform xml -> json
var x2js = new X2JS();
var json = x2js.xml_str2json(_rdata);
//console.log("XML DATA: " + _rdata);
//console.log("JSON DATA: " + JSON.stringify(json));
var _webs = json.Envelope.Body.GetWebCollectionResponse.GetWebCollectionResult.Webs.Web;
// if response has [] of webs - array of objects / sites
if ($(_webs).length > 0 && $.isArray(_webs)) {
$.each(_webs, function (key) {
// loop and build tree
mData.children.push({
name: "Site: " + _webs[key]._Title,
url: _webs[key]._Url,
children: []
});
// recursive loop call for each site again
$scope.processTree(mData.children[key]);
});
}
// if response has {} of webs - single object / site
else if ($.isPlainObject(_webs)) {
mData.children.push({
name: _webs._Title,
url: _webs._Url,
children: []
});
}
// if no response or response is null, do nothing
else {
}
}, function(msg){
alert("ERROR!!! \n\nERROR DATA: " + msg[0] + " \tStatus: " + msg[1]);
});
};
function callback(mData){
// do something - use mData, create tree html and display
}
The recursion gathers all sites and subsites for each site, storing them in a variable called mData. My challenge now is to return and utilize this variable as JSON input to construct a tree map once the entire recursion process is completed. Each async call either returns an array of sites or a single site.
How can I ensure that mData is returned only after the full recursion is finished? What indicators can be used to determine when the recursion has concluded so that a call can be made to the desired function?