[英]Async / Await function not awaiting
在這里,我正在嘗試制作一個 function ,它使用 MVC 模式從數據庫中檢索一些數據。
看法
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
})
}
我確實希望在控制台中讀取此序列中的數字:1、2、3、4、5、6、7、8、9、10。相反,控制台中打印的序列是:1、2、3、4, 5、6、10、7、8、9。
這意味着模型的 function "getQuestionChoices" 不等待返回語句。
我怎樣才能解決這個問題?
謝謝
這個:
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
})
返回一個 promise 數組,並且結果沒有分配到任何地方
修復:
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
}))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.