Reputation: 11
May I know is there a way to walk/traverse tree asynchronously using tree-model-js. There is a walk function in tree-model-js. However, it seems it is not an aync function.
Basically, I have some aync processes to process each node of the tree. 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.
If tree-model-js don't have such function, is there a way to traverse my datatree asynchronously ?
Upvotes: 1
Views: 795
Reputation: 711
tree-model-js does not support async traversal. 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. I've used the Q library for promises because I'm familiar with it.
Not sure if this helps with your use-case. You can play with this code here.
Upvotes: 2