节点猫鼬在循环中查找查询不起作用
我正在尝试从循环中的猫鼬中获取记录.但是它没有按预期工作.我有一系列带有问题和答案的哈希,我正尝试从数据库中查找那些问题.这是我的循环:
I am trying to fetch records from mongoose in loop. But it is not working as expected. I have an array of hashes with questions and answers and I'm trying to find those questions from my db. Here is my loop:
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
}
})
}
,终端的结果类似于:
0
t
1
f
[ { question: 'i was here',
_id: 5301da79e8e45c8e1e7027b0,
__v: 0,
f: [ 'E', 'N', 'F' ],
t: [ 'E', 'N', 'F' ] } ]
[ { question: 'WHo r u ',
_id: 5301c6db22618cbc1602afc3,
__v: 0,
f: [ 'E', 'N', 'F' ],
t: [ 'E', 'N', 'F' ] } ]
问题是我的问题在循环迭代后显示.因此,我无法处理它们.
The problem is that my questions are displaying after loop's iteration. And because of that I am unable to process them.
请帮助! 问候
欢迎来到异步领域:-)
Welcome to async-land :-)
使用JavaScript,除了您的代码外,任何其他事情都是并行发生的.这意味着在您的特定情况下,无法在循环结束之前调用回调.您有两种选择:
With JavaScript anything happens in parallel except your code. This means in your specific case, that the callbacks cannot be invoked before your loop has ended. You have two options:
a)将循环从同步for循环重写为异步递归循环:
a) Rewrite your loop from a sync for-loop to an async recurse-loop:
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
});
此外,我建议您研究此博客.它在异步循环阶梯上又包含两个步骤.非常有帮助,非常重要.
Additionally I recommend the study of this blog. It contains two further steps up the async-loop-stairway. Very helpful and very important.
b)将您的异步函数调用放入格式为
b) Put your async function call into a closure with format
(function( ans ) {})(ans);
并为其提供要保留的变量(此处为ans
):
and provide it with the variable you want to keep (here: 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);
}