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

nOm*_*Omi 7 mongoose mongodb node.js

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

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      
        }
    })
}
Run Code Online (Sandbox Code Playgroud)

和终端的结果是这样的:

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' ] } ]
Run Code Online (Sandbox Code Playgroud)

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

请帮忙!问候

hei*_*nob 17

欢迎来到async-land :-)

使用JavaScript除了代码之外,任何事情都会并行发生 这意味着在您的特定情况下,在循环结束之前无法调用回调.您有两种选择:

a)将同步for循环的循环重写为异步recurse循环:

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
});
Run Code Online (Sandbox Code Playgroud)

此外,我建议研究这个博客.它包含了async-loop-stairway的两个进一步的步骤.非常有帮助,非常重要.

b)将异步函数调用放入带格式的闭包中

(function( ans ) {})(ans);
Run Code Online (Sandbox Code Playgroud)

并为它提供你想要保留的变量(这里:) 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);
}
Run Code Online (Sandbox Code Playgroud)