[英]Async / Await function not awaiting
here I am trying to make a function which retrieves some data from a database by using MVC pattern.在这里,我正在尝试制作一个 function ,它使用 MVC 模式从数据库中检索一些数据。
View看法
getQuestionsData (treatmentId) {
console.log(1)
controller.getTreatmentQuestions(treatmentId)
.then(questions => {
console.log(10)
this.questions = questions // variable is updated
})
},
Controller 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 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.我确实希望在控制台中读取此序列中的数字:1、2、3、4、5、6、7、8、9、10。相反,控制台中打印的序列是:1、2、3、4, 5、6、10、7、8、9。
This means that model's function "getQuestionChoices" is not waiting for return statement.这意味着模型的 function "getQuestionChoices" 不等待返回语句。
How can I fix this?我怎样才能解决这个问题?
Thank you谢谢
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返回一个 promise 数组,并且结果没有分配到任何地方
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
}))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.