I am using NodeJS (ExpressJS) server, have the following code:
let caseScore = 0
await questions.map(async q => {
caseScore += await q.grade() // Queries database and gets questions, finds score
}))
console.log(caseScore)
>> Output: 0
However, it appears that q.grade() finishes executing after the request is finished. I put a console.log() within q.grade, and it shows up after response is sent. Clearly this is executed asynchronously. So later I did this:
let caseScore = 0
await Promise.all(questions.map(async q => {
caseScore += await q.grade() // Queries database and gets questions, finds score
})))
console.log(caseScore)
>> Output: 2
It works perfectly. Can someone explain to me why Promise.all is needed? Also, if I switch .map for .forEach, Promise.all errors, what is the correct way to do this for .forEach?