节点mongoose查找循环中的查询不工作

我正试图从循环中获取mongoose的logging。 但是它没有按预期工作。 我有一系列的问题和答案哈希,我试图从我的数据库中find这些问题。 这是我的循环:

for (var i=0;i < answers.length;i++) { console.log(i) var question_ans = eval('(' + answers[i]+ ')'); var question_to_find = question_ans.question.toString() var ans = question_ans.ans.toString() console.log(ans) quiz.where("question",question_to_find).exec(function(err,results) { console.log(results) if (ans == "t") { user_type = results.t } else if (ans == "f") { user_type=results.f } }) } 

和terminal的结果是这样的:

 0 t 1 f [ { question: 'i was here', _id: 5301da79e8e45c8e1e7027b0, __v: 0, f: [ 'E', 'N', 'F' ], t: [ 'E', 'N', 'F' ] } ] [ { question: 'WHo ru ', _id: 5301c6db22618cbc1602afc3, __v: 0, f: [ 'E', 'N', 'F' ], t: [ 'E', 'N', 'F' ] } ] 

问题是我的问题在循环迭代后显示。 正因为如此,我无法处理它们。

请帮忙! 问候

欢迎来到async-land 🙂

使用JavaScript,除了你的代码之外,任何事情都是平行的 这意味着在您的具体情况下,在循环结束之前,不能调用callback。 你有两个select:

a)将你的循环从同步for循环重写到asynchronousrecursion循环:

 function asyncLoop( i, callback ) { if( i < answers.length ) { console.log(i) var question_ans = eval('(' + answers[i]+ ')'); var question_to_find = question_ans.question.toString() var ans = question_ans.ans.toString() console.log(ans) quiz.where("question",question_to_find).exec(function(err,results) { console.log(ans, results) if (ans == "t") { user_type = results.t } else if (ans == "f") { user_type=results.f } asyncLoop( i+1, callback ); }) } else { callback(); } } asyncLoop( 0, function() { // put the code that should happen after the loop here }); 

此外,我build议研究这个博客 。 它包含asynchronous循环楼梯的另外两个步骤。 非常有帮助,非常重要。

b)把你的asynchronous函数调用放到一个格式化的闭包中

 (function( ans ) {})(ans); 

并提供你想要保留的variables(在这里: ans ):

 for (var i=0;i < answers.length;i++) { console.log(i) var question_ans = eval('(' + answers[i]+ ')'); var question_to_find = question_ans.question.toString() var ans = question_ans.ans.toString() console.log(ans) (function( ans ) { quiz.where("question",question_to_find).exec(function(err,results) { console.log(ans, results) if (ans == "t") { user_type = results.t } else if (ans == "f") { user_type=results.f } }) })(ans); }