2017-03-05 99 views
1

我试图从2回调传递2个结果到lodash函数(_.union)使用递归函数。 我不明白我做错了什么!我一直在“未定义”。 这里是我的代码:NodeJS:具有异步请求的递归函数

  • 编辑:

我与 “承诺” 技术

,入住在远程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 
     }) 
    }) 
} 

主要功能:

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

现在,功能findFile()console.log什么样的回报,我需要里面。但后来我需要在另一个函数(union)中使用这两个返回的值,并且它返回undefined

在主线程

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

现在我敢肯定:不顺心的递归函数和节点的异步错...

我需要它来递归地工作,并能得到这样复杂的表达式:

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

做一些知道什么是写它要么无线的正确方法th Promiseasync.waterfall ?? 在此先感谢!

+2

可能的重复[如何返回来自异步调用的响应?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-调用) – gyre

回答

1

您的代码不起作用,因为您试图以同步方式获取异步响应。

看看承诺。

+0

你知道用async.waterfall编写它的正确方法是什么? – DavidA

+0

你可以在你的'query'函数中传递一个回调或者使用promise,并且在完成瀑布回调后调用回调,基本上解决你在瀑布调用中的承诺:https://www.npmjs.com/package/async-waterfall #tasks-as-array-of-functions – Nijikokun

+0

谢谢你,我已经看到了。仍然不知道如何将它与我的代码... :( – DavidA