Javascript async Wait中的代码执行顺序在nodejs中的函数中不能正常工作?
我也在用expressJs编写一个带有数据库调用的函数,但我不明白为什么 尽管使用了async await,但以下语句给出的值为0: 在这个控制台语句countRight中,countError的值为零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
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()
,本文将提供更多信息。()