javascript - 异步/等待功能不等待
问题描述
在这里,我正在尝试创建一个使用 MVC 模式从数据库中检索一些数据的函数。
看法
getQuestionsData (treatmentId) {
console.log(1)
controller.getTreatmentQuestions(treatmentId)
.then(questions => {
console.log(10)
this.questions = questions // variable is updated
})
},
控制器
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
}
模型
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。
这意味着模型的函数“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
}))
推荐阅读
- c++ - 使用模板在 C++ 中编译排序的链接列表对象/类时链接器命令失败
- asp.net-core-webapi - .NET Core 3.1 WebAPI IISExpress 在调试时挂起
- r - 导入数据时出现数字错误
- java - Android Studio:房间中的插入功能未正确存储实体
- php - Live Server 无法加载其他页面并出现 Apache 404 错误
- reactjs - 反应:尝试用 src/ 镜像 __tests__/
- javascript - 评论按钮在 jquery 函数中不起作用
- javascript - 对网站的 Http 请求以获取特定 html 元素的内容
- python - 检查对象是否在python c扩展中是可迭代的
- c - 链接器抱怨可能未初始化的变量(完全优化的构建选项)