我正在尝试使用递归函数将 2 个结果从 2 个回调传输到 1 个 lodash 函数 (_.union)。。 我不明白我做错了什么!我不断得到“未定义”。 这是我的代码:
- 已编辑:
我使用“promise”技术的新代码
第一个检查远程数据库中内容的函数-
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
返回我需要的内容。但随后我需要在另一个函数(联合)中使用两个返回值,并且它返回未定义。
在主线程中:
searchOperation('Expression1 OR Expression2', function(result){
res.json(result);
})
现在我确定:递归函数和 Node 异步出了问题...
我需要它递归地工作,并且可能会得到复杂的表达式,例如:
'((A NOT B) AND (C OR D))'
有人知道用 Promise
或 async.waterfall
编写它的正确方法是什么吗??
提前致谢!!!
最佳答案
您的代码不起作用,因为您试图以同步方式获取异步响应。
研究 promise 。
关于javascript - NodeJS : recursive function with async request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42606247/