I am new to promises. I have to traverse a tree that returns a promise from its getNode
function. I have successfully found the first call to root using the prom.then(....)
.
However, the next step doesn't work. Specifically the recursive call returns undefined on the line:
leftTree = inOrderPromise(ptree,leftIndex);
The code correctly calls the function again, and getting the correct node into root, but I can't figure out how to combine my answers. How would I do this?
TYIA
PromiseTree.prototype.getNode = function (index, callback) {
return Promise.resolve(this.data[index]);
};
var inOrderPromise = function(ptree, rootIndex){
var prom = ptree.getNode(rootIndex,function(){});
prom.then(function(root){
var leftTree = [];
if(root.left){//if node has a left, recursively traverse
var leftIndex = root.left;
leftTree = inOrderPromise(ptree, leftIndex);
}
var rightTree = [];
if(root.right){//if node has a right, recursively traverse
var rightIndex = root.right;
rightTree = inOrderPromise(ptree, rightIndex);
}
//results: leftTree, root, rightTree
console.log(leftTree.concat(root.value).concat(rightTree));
return leftTree.concat(root.value).concat(rightTree);
});
}