簡體   English   中英

使用tree-model-js異步遍歷樹

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

我可以知道是否有一種使用tree-model-js異步遍歷/遍歷樹的方法。 tree-model-js中有一個walk函數。 但是,它似乎不是aync函數。

基本上,我有一些aync進程來處理樹的每個節點。 我需要一種方法來aync遍歷數據樹,以確保每個aync進程都以特定順序發生(例如:預排序),並在遍歷該樹時使用回調返回最終結果。

如果tree-model-js沒有這種功能,是否可以異步遍歷我的數據樹?

tree-model-js不支持異步遍歷。 但是,您仍然可以為每個訪問的節點編寫或調用異步代碼。

如果我正確理解了您的問題,則需要等待父級長任務完成后再調用子級長任務。 這可能對您有幫助:

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

注意, asyncWalk函數為從根到葉的每個路徑組成一個promise,然后同時執行這些組成的promise。 我已經使用Q庫實現了諾言,因為我對此很熟悉。

不確定這是否對您的用例有用。 您可以在此處使用此代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM