1

I am writing a function in expressJs with database calls too but I am unable to understand why even though async await is used the following statement is giving 0 value: In this console statement countRight, countWrong is giving value as zero.

console.log("End...", countRight, countWrong);

The code block is below:

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);
}

I am confused completely why the values are not coming.

Kabeer Singh
  • 133
  • 1
  • 7
  • 2
    Use `for of` loop instead of `forEach()` method. `forEach()` won't wait for one async call to finish before calling the callback again. You could also use `Promise.all` if you want to make parallel async calls. – Yousaf Oct 12 '20 at 12:18
  • @KabeerSingh If you want a detailed explanation as to why `forEach()` isn't suited to your case, and another possible solution, which is to create your own `asyncforEach()`, this article is more informative. (https://codeburst.io/javascript-async-await-with-foreach-b6ba62bbf404) – Ryan Wilson Oct 12 '20 at 12:26

1 Answers1

2

The answer to your question lies in the way you are using async await inside loops.

Never I mean never use async await inside for-each loop. you have to use for … of loop if you want to get the answer.

The below code should work::

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};    
}
arjun sah
  • 407
  • 3
  • 11