Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript async Wait中的代码执行顺序在nodejs中的函数中不能正常工作?_Javascript_Express_Async Await - Fatal编程技术网

Javascript async Wait中的代码执行顺序在nodejs中的函数中不能正常工作?

Javascript async Wait中的代码执行顺序在nodejs中的函数中不能正常工作?,javascript,express,async-await,Javascript,Express,Async Await,我也在用expressJs编写一个带有数据库调用的函数,但我不明白为什么 尽管使用了async await,但以下语句给出的值为0: 在这个控制台语句countRight中,countError的值为零 console.log("End...", countRight, countWrong); 代码块如下所示: exports.finishQuiz = async (req) => { let eid = req.params.quizId; con

我也在用expressJs编写一个带有数据库调用的函数,但我不明白为什么 尽管使用了async await,但以下语句给出的值为0: 在这个控制台语句countRight中,countError的值为零

console.log("End...", countRight, countWrong);
代码块如下所示:

exports.finishQuiz = async (req) => {
    let eid = req.params.quizId;
    const {selectedAnswers} = req.body;
    let countRight = 0;
    let countWrong = 0;
    let answer;
    console.log("Start...");
    selectedAnswers.forEach(async function(el) {
        answer = await answerModal.findOne({
           where :{qid: el.qid}
        });
        answer = answer.toJSON().answerValue;
        // counter to calculate right and wrong.
        
        if(el.answerSelected.trim() === answer.trim()){
            countRight = countRight + 1;

        }
        else{
            countWrong = countWrong + 1;
        }
        
    });
    // calculate number of right answer
    // and wrong answer
    console.log("End...", countRight, countWrong);
}


我完全搞不懂为什么没有这些值。

您的问题的答案在于您在循环内使用异步等待的方式

我的意思是永远不要在每个循环中使用异步等待。 如果要得到答案,必须使用
for…of
循环

下面的代码应该可以工作:

exports.finishQuiz = async (req) => {
    let eid = req.params.quizId;
    const {selectedAnswers} = req.body;
    let countRight = 0;
    let countWrong = 0;
    let answer;
    console.log("Start...");
    for (let el of selectedAnswers) {
        answer = await answerModal.findOne({
           where :{qid: el.qid}
        });
        answer = answer.toJSON().answerValue;
        // counter to calculate right and wrong.
        
        if(el.answerSelected.trim() === answer.trim()){
            countRight = countRight + 1;
        }
        else{
            countWrong = countWrong + 1;
        }
        
    };
    // calculate number of right answer
    // and wrong answer
    // calculate score
    console.log("End...", countRight, countWrong);
    return { countRight, countWrong};    
}

使用
for of
循环,而不是
forEach()
方法
forEach()
在再次调用回调之前不会等待一个异步调用完成。如果您想进行并行异步调用,还可以使用
Promise.all
。@KabeerSingh如果您想详细解释为什么
forEach()
不适合您的情况,以及另一种可能的解决方案,即创建您自己的
asyncfeach()
,本文将提供更多信息。()