简体   繁体   English

JavaScript:具有Promise的递归函数,resolve返回“ undefined”

[英]JavaScript: Recursive function with Promise, resolve returns “undefined”

I have a recursive function which is returning promise, there is some conditions which on fulfillment the resolve will fire. 我有一个递归函数,它返回promise,在满足条件的情况下,解析将触发某些条件。 But the resolve always returns undefined. 但是解析总是返回未定义的。

Here is the code: 这是代码:

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

I'm trying to get all children of a Representative and the children of its children (if any) and return them all. 我正在设法让代表的所有子代及其代表的子代(如果有)全部归还。

What is it that I'm doing wrong? 我做错了什么事?

Any help would be much appreciated. 任何帮助将非常感激。

Thanks in advance. 提前致谢。

You are making things slightly complicated. 您使事情变得有些复杂。 I think what you want to achieve is to use promise to return a result from a recursive function. 我认为您想要实现的是使用Promise从递归函数返回结果。 Here's a cleaner version 这是一个更清洁的版本

A cleaner solution - 清洁的解决方案-

getRelationsOfRep(repId) {
    return new Promise( function(resolve,reject) {
          recursiveFunctionCall(repId);
          function recursiveFunctionCall(repId) {
             //your recursive function logic
             recursiveFunctionCall(childId);
             if(...) //edge case condition
               resolve('your-answer');
             else 
               reject('your-error')
          }
    });

This way, you'll just be using one promise and returning when your recursive function resolves. 这样,您将只使用一个promise并在递归函数解析后返回。

Use Promise.all() to capture all the promises in Loop. 使用Promise.all()捕获Loop中的所有promise。

Instead of: 代替:

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

Try: 尝试:

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

Using something like this, you will be able to get nested response for the recursive calls. 使用类似的方法,您将能够获得递归调用的嵌套响应。

PS Not tested, modify according to the logic you want. PS未测试,请根据所需逻辑进行修改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM