简体   繁体   English

使用tree-model-js异步遍历树

[英]Asynchronously tree traversal using tree-model-js

May I know is there a way to walk/traverse tree asynchronously using tree-model-js. 我可以知道是否有一种使用tree-model-js异步遍历/遍历树的方法。 There is a walk function in tree-model-js. tree-model-js中有一个walk函数。 However, it seems it is not an aync function. 但是,它似乎不是aync函数。

Basically, I have some aync processes to process each node of the tree. 基本上,我有一些aync进程来处理树的每个节点。 I need a way to aync traverse the data tree to make sure every aync process happened in certain order (eg: pre-order) and return the final result using a callback upon finish traversing the tree. 我需要一种方法来aync遍历数据树,以确保每个aync进程都以特定顺序发生(例如:预排序),并在遍历该树时使用回调返回最终结果。

If tree-model-js don't have such function, is there a way to traverse my datatree asynchronously ? 如果tree-model-js没有这种功能,是否可以异步遍历我的数据树?

tree-model-js does not support async traversal. tree-model-js不支持异步遍历。 But, you can still compose or call your async code for each visited node. 但是,您仍然可以为每个访问的节点编写或调用异步代码。

If I understood your question correctly, you need to wait for the parent long task to finish before calling the child long task. 如果我正确理解了您的问题,则需要等待父级长任务完成后再调用子级长任务。 This might help you: 这可能对您有帮助:

var tree = new TreeModel();

var root = tree.parse({
    id: 1,
    children: [
        {
            id: 11,
            children: [{id: 111}]
        },
        {
            id: 12,
            children: [{id: 121}, {id: 122}]
        },
        {
            id: 13
        }
    ]
});

function longTask(node) {
  // Some long running task
  console.log("Running long task on node " + node.model.id);

  // Fake result
  return "res=" + node.model.id;
}

function asyncWalk(node) {
  var leafPromises = [];
  var promisesTemp = {};

  node.walk(function (node) {
    var nodePromise;
    if (node.isRoot()) {
      nodePromise = Q.fcall(function () {
        return [longTask(node)];
      });
    } else {
      nodePromise = promisesTemp[node.parent.model.id].then(function (prevResult) {
        return prevResult.concat(longTask(node));
      });
    }

    if (!node.hasChildren()) {
      leafPromises.push(nodePromise);
    } else {
      promisesTemp[node.model.id] = nodePromise;
    }
  });

  return Q.all(leafPromises);
}

// Using our async walk function...
asyncWalk(root).then(function (leafPromisesResult) {
  leafPromisesResult.forEach(function (leafPromiseResult) {
    console.log("ordered results: " + leafPromiseResult);
  });
});

Note the asyncWalk function composes a promise for each path from root to leaf and then executes each of these composed promises concurrently. 注意, asyncWalk函数为从根到叶的每个路径组成一个promise,然后同时执行这些组成的promise。 I've used the Q library for promises because I'm familiar with it. 我已经使用Q库实现了诺言,因为我对此很熟悉。

Not sure if this helps with your use-case. 不确定这是否对您的用例有用。 You can play with this code here . 您可以在此处使用此代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM