DavidA
DavidA

Reputation: 628

NodeJS: recursive function with async request

I'm trying to transfer 2 results from 2 callback to 1 lodash function (_.union) using recursive function. I dont understand what am I doing wrong! I keep getting "undefined". Here is my code:

My new code with the "promise" technique

the first function that check things in the remote DB-

function findFiles(kw, callback){
    if (_.isArray(kw)) {return callback(kw)};

    return new Promise((resolve, reject) => {
        console.log(kw);
        word.aggregate([
                     { $match: { keyWord: kw } },
                     { $project: { filesFound: '$filesFound.fileName' , '_id':0} },
                     { $sort: { fileName: 1 } }
                   ],function(err, obj){
                    console.log('checked' + kw);
                    console.log(obj);
            if (err) return reject(err);
            else      
                return resolve(obj[0].filesFound);//obj[0].filesFound
        })
    })
}

The main function:

    function searchOperation(query, callback){
    var stack=[];
    if (!(_.includes(query, 'OR')) && !(_.includes(query, 'AND')) && !(_.includes(query, 'NOT'))){

        findFiles(query)
        .then((item) => {
            console.log(item+'********');   
           callback(item)
        })
        .catch((err) => {
          console.log(err)
        })
    }
    else{
        wordsArr = _.split(query, " ");
        console.log("+++++:" + wordsArr);
        wordsArr.forEach(function(w){
            console.log('first check:'+w);

            if(_.isEmpty(stack)){

                if(_.includes(w, 'OR')){
                    console.log('found OR');
                    var statement = [];
                    console.log('query is:'+query);
                    statement = _.split(query, w, 2);
                    console.log(statement[0]+' , '+statement[1]);
                    return new Promise((resolve, reject)=>{


    resolve(_.union(searchOperation(statement[0]),searchOperation(statement[1])))
                        })
//ANOTHER OPTION:
                        // searchOperation(statement[0],function(arr1){
                        //     console.log('arr1');
                        //     console.log('done part 1!');
                        //     searchOperation(statement[1],function(arr2){
                        //         console.log('who called arr2?');
                        //         return(_.union(arr1,arr2));
                        //     })
                        // });
                    }
                }
            })
        }
    }

now, inside the function findFile() the console.log return what i need. but then I need to use both returned values in another function (union) and it returns undefined.

in the main thread:

searchOperation('Expression1 OR Expression2', function(result){
    res.json(result);
})

now i'm sure: something goes WRONG in the recursive function and the async of node...

I need it to work recursively and could get complicate expressions like:

'((A NOT B) AND (C OR D))' 

does some know what is the right way to write it either with Promise or async.waterfall ?? thanks in advance!!!

Upvotes: 1

Views: 251

Answers (1)

Nijikokun
Nijikokun

Reputation: 1524

Your code doesn't work because you're trying to get an Async response in a Synchronous fashion.

Look into Promises.

Upvotes: 1

Related Questions