如何等待forEach循环执行的所有递归函数调用都完成

时间:2017-01-16 11:11:23

标签: javascript

我怎样才能在代码中的所需位置等待,直到treeData上的所有处理完成为止?

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

1 个答案:

答案 0 :(得分:0)

  1. 最简单的方法是添加一个函数调用计数器
  2. 执行所有函数调用后,请使用回调并继续进行。
  3. 
    
    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);
      }
    }