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);
  }
}
4
  • 1
    stackoverflow.com/questions/21518381/…
    – Pingbeat
    Commented Jan 16, 2017 at 11:13
  • 1
    use callback functions. You can visit this link to know about callbacks.
    – Shubham
    Commented Jan 16, 2017 at 11:14
  • 1
    Have a look at promises on MDN. No IE support though.
    – RobG
    Commented Jan 16, 2017 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
    Commented Jan 19, 2017 at 15:05

1 Answer 1

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);
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.