I have this scoring routine that first checks for unanswered questions, and renders either the review or the score depending on if there are unanswered questions remaining.
The problem is it is running asynchronously, so the score is being calculated even when there are unanswered questions.
I know there are a bunch of hacky ways to fix this, but it seems like a Promise would be a good solution. I’m having trouble understanding what the promise is, if anything needs to be chainned, what needs to be pre-defined and how the syntax should work:
Original Code
handleScore () {
//check for unanswered
this.checkUnanswered()
//score the test
console.log ("Scoring your test")
if (this.state.unansweredQuestions.length===0) {
let score = this.state.selectedAnswers.reduce((totalScore, answer, i) => {
console.log("Answer " + i + " = " + answer)
if (answer === this.state.answerKey[i]) {
totalScore++
} else {
}
return totalScore
}, 0
)
this.setResults(score)
console.log("Your score is: ", score)
}
}
checkUnanswered () {
let unansweredQuestions = this.state.selectedAnswers.map((answer, i) => {
if (answer === 0 ) {
return i
} else {
return null
}
}).filter((el) => {
return el
})
if (unansweredQuestions.length>0) {
this.setState({
unansweredQuestions: unansweredQuestions,
reviewMode: true
})
}
// console.log("Unanswered: " + unanswered)
console.log("Unanswered Questions:" + unansweredQuestions)
console.log("Length of array: " + unansweredQuestions.length)
}