我试图从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 Promise
或async.waterfall
?? 在此先感谢!
可能的重复[如何返回来自异步调用的响应?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-调用) – gyre