从promise中调用递归函数

时间:2017-11-21 06:49:08

标签: javascript recursion promise

我是承诺的新手。我必须遍历一个从getNode函数返回一个promise的树。我使用prom.then(....)成功找到了第一次调用root。

但是,下一步不起作用。具体来说,递归调用在行上返回undefined:

 leftTree = inOrderPromise(ptree,leftIndex);

代码再次正确调用该函数,并将正确的节点转换为root,但我无法弄清楚如何组合我的答案。我该怎么做?

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

1 个答案:

答案 0 :(得分:0)

使用生成器函数,它们用于基本上执行异步迭代更容易,它们也可以很好地与promises一起使用。您可能需要稍微调整一下代码,我没有运行它,但它正朝着正确的方向运行。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators

PromiseTree.prototype.getNode = function (index, callback) {
    return Promise.resolve(this.data[index]);
};

function *inOrderPromise(ptree, rootIndex){
        var root = yield ptree.getNode(rootIndex);
        var leftTree = [];
        if(root.left){
            leftTree = yield *inOrderPromise(ptree, root.left);
        }
        var rightTree = [];
        if(root.right){
            rightTree = yield *inOrderPromise(ptree, root.right);
        }


        //results: leftTree, root, rightTree
        console.log(leftTree.concat(root.value).concat(rightTree));
        return leftTree.concat(root.value).concat(rightTree);
}