首页 > 解决方案 > JavaScript:带有 Promise 的递归函数,解析返回“未定义”

问题描述

我有一个返回承诺的递归函数,有一些条件会在完成时触发。但是解析总是返回未定义的。

这是代码:

var children = [];
var temp = [];
function getRelationsOfRep(repId) {
    var index;
    return new Promise(function (resolve, reject) {
        return RepRelation.findOne({_id: repId}).then(function (repData) {
            if (<condition>) {
                temp = temp.concat(repData.children);
                temp.forEach(function (childId) {
                    return getRelationsOfRep(childId);
                });
            } else {
                // else
            }
            if (<another condition>) {
                return resolve(children);
            }
        }).catch(function (error) {
            return reject(error);
        })
    })
}

function updateRepData(id){
    children = [];
    temp = [];
    getRelationsOfRep(id).then(function (branchesData) {
        console.log('branchesData:: ', branchesData); // it prints undefined
    })
}

我正在尝试获取代表的所有孩子及其孩子的孩子(如果有的话)并将它们全部归还。

我做错了什么?

任何帮助将非常感激。

提前致谢。

标签: javascriptrecursionpromise

解决方案


使用 Promise.all() 捕获 Loop 中的所有 Promise。

代替:

temp.forEach(function (childId) {
    return getRelationsOfRep(childId);
});

尝试:

var promisesArray = [];
temp.forEach(function (childId) {
    promisesArray.push(getRelationsOfRep(childId));
});
return Promise.all(promisesArray);

使用这样的东西,您将能够获得递归调用的嵌套响应。

PS 未测试,根据你想要的逻辑修改。


推荐阅读