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.