简体   繁体   中英

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. 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. 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.

Use Promise.all() to capture all the promises in Loop.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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