Search code examples
javascriptasync-awaitdexie

Async / Await function not awaiting


here I am trying to make a function which retrieves some data from a database by using MVC pattern.

View

getQuestionsData (treatmentId) {

  console.log(1)

  controller.getTreatmentQuestions(treatmentId)
    .then(questions => {

      console.log(10)

      this.questions = questions   // variable is updated
    })
},

Controller

getTreatmentQuestions: async (treatmentTypeId) => {

  console.log(2)

  // first data fetch from db
  const questions = await model.getQuestion(treatmentTypeId)

  console.log(3)

  // iterate over each result record
  questions.map(async question => {

    console.log(4)

    if (question.answerType === 'select') {

      console.log(5)

      // second data fetch from db
      const answerWithChoices = await model.getQuestionChoices(question.id)

      console.log(9)

      // update question object with fetched data
      question = Object.assign({}, question, {
        choices: answerWithChoices.choices
      })
    }

    return question
  })

  return questions
}

Model

static async getQuestionChoices (questionId) {
  console.log(6)
  const answers = await db.choiceAnswers
    .where('questionId').equals(intId)
    .with({
      selectChoices: 'choiceAnswersChoices'
    })

  console.log(7)

  return answers.map(answer => {

    console.log(8)

    answer.choices = answer.selectChoices

    return answer
  })
}

I do expect to read in console the numbers in this sequence: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10. Instead, the sequence printed in console is: 1, 2, 3, 4, 5, 6, 10, 7, 8, 9.

This means that model's function "getQuestionChoices" is not waiting for return statement.

How can I fix this?

Thank you


Solution

  • This:

     questions.map(async question => {
    
        console.log(4)
    
        if (question.answerType === 'select') {
    
          console.log(5)
    
          // second data fetch from db
          const answerWithChoices = await model.getQuestionChoices(question.id)
    
          console.log(9)
    
          // update question object with fetched data
          question = Object.assign({}, question, {
            choices: answerWithChoices.choices
          })
        }
    
        return question
      })
    

    Returns an array of promises and the result is not assigned anywhere

    The fix:

     questions = await Promise.all(questions.map(async question => {
    
        console.log(4)
    
        if (question.answerType === 'select') {
    
          console.log(5)
    
          // second data fetch from db
          const answerWithChoices = await model.getQuestionChoices(question.id)
    
          console.log(9)
    
          // update question object with fetched data
          question = Object.assign({}, question, {
            choices: answerWithChoices.choices
          })
        }
    
        return question
      }))