【问题标题】:How to wait until all recursive function calls executed by forEach loop are finished如何等待 forEach 循环执行的所有递归函数调用完成
【发布时间】:2023-04-08 13:53:01
【问题描述】:

如何在代码中的所需位置等待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);
  }
}

【问题讨论】:

  • 使用回调函数。您可以访问此link 了解回调。
  • 看看promises on MDN。不过不支持 IE。
  • @Pingbeat @Shubham 我看了一下回调的概念。但是由于toggleAll() 的嵌套递归调用,我很难对我的示例采用回调方法。应该给哪个函数回调,什么时候执行回调?

标签: javascript


【解决方案1】:
  1. 最简单的方法是添加一个函数调用计数器
  2. 在执行所有函数调用时,使用回调并继续进行。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-23
    • 2017-06-22
    • 2019-04-15
    • 2022-01-27
    • 2016-09-09
    • 2022-01-23
    • 2021-03-21
    • 1970-01-01
    相关资源
    最近更新 更多