0

How can I wait at the desired place in the code until all the processing on treeData is finished?

var treeData = $scope.rawData;

if ($scope.treeExpanded) {
  //expand tree
  if (treeData && treeData.children) {
    treeData.children.forEach(toggleAll);
  }

  //how to wait here until all recursion calls are finished?
  //console.log(treeData) will show a non modified object equals to $scope.rawData

}

function toggle(d) {
  if (d.children) {
    d._children = d.children;
    d.children = null;
  }
}

function toggleAll(d) {
  if (d && d.children) {
    d.children.forEach(toggleAll);
    toggle(d);
  }
}
d4rty
  • 3,970
  • 5
  • 34
  • 73
  • 1
    http://stackoverflow.com/questions/21518381/proper-way-to-wait-for-one-function-to-finish-before-continuing – Pingbeat Jan 16 '17 at 11:13
  • 1
    use callback functions. You can visit this [link](http://recurial.com/programming/understanding-callback-functions-in-javascript/) to know about callbacks. – Shubham Jan 16 '17 at 11:14
  • 1
    Have a look at [*promises* on MDN](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise). No IE support though. – RobG Jan 16 '17 at 11:15
  • @Pingbeat @Shubham I took a look at the concept of callbacks. But I have difficulties to adopt the approach of callbacks to my example, due to the nested recursive calls of `toggleAll()`. Which function should I give the callback and when should I execute the callback? – d4rty Jan 19 '17 at 15:05

1 Answers1

0
  1. Simplest way is to add a function call counter
  2. On execution of all your function calls, use your callback and proceed further.

var treeData = $scope.rawData, callCompleted;

if ($scope.treeExpanded) {
  //expand tree
  if (treeData && treeData.children) {
    callsCompleted = 0;
    treeData.children.forEach(toggleAll);
  }

  //how to wait here until all recursion calls are finished?
  //console.log(treeData) will show a non modified object equals to $scope.rawData

}

function toggleCompleted() {
    // Do your processing here...
}

function toggle(d, noOfCalls, callBack) {
  if (d.children) {
    d._children = d.children;
    d.children = null;
    callsCompleted += 1;
    if(noOfCalls === callsCompleted) {
        // all calls are completed
        callBack();
    }
  }
}

function toggleAll(d) {
  if (d && d.children) {
    d.children.forEach(toggleAll);
    toggle(d, d.length, trackToggleCompletion);
  }
}
psycho
  • 102
  • 8