javascript - Promise 链:父 Promise 不会等到子 Promise 被执行
问题描述
我从一个 mongoDB 集合中获取数据,在该响应中,我得到了另一个集合数据的 Id 并获取它并将其合并到一个对象中。
这是我的代码,但不是等待 unitl child primise 被执行。
指导我的代码错误。
Courses.find({})
.then( course => {
//getting data from one collection
let CoursePromises = course.map(
key => {
new Promise((resolve, reject) => {
key.questions = []
//getting data from another collection via Id fetched from first collection.
let getQuestionsPromises = key.questionIds.map(
ques =>
new Promise((resolve, reject) => {
Questions.find({_id: ques._id})
.then(question => {
resolve(question)
}).catch(err => {
console.error("Error in question ", err.message)
})
})
)
Promise.all(getQuestionsPromises).then((data) => {
key.questions.push(data)
console.log("getQuestionsPromises", key)
})
resolve(key)
})
})
Promise.all(CoursePromises).then((data) => {
console.log("CoursePromises") // here promise is now wait for exection done
res.send({ status: true, data: course })
}
)
我得到了这样的第一个收集响应:
{
"status": true,
"data": [
{
"_id": "5e3c1b683ac31f24da39e50a",
"courseName": "Test",
"duration": 1,
"createdBy": "John Die",
"__v": 0,
"updatedAt": "2020-02-06T13:58:00.906Z",
"createdAt": "2020-02-06T13:58:00.906Z",
"isAssigned": false,
"questions": []
"questionIds": [
{
"index": 1,
"_id": "5e3c1b683ac31f24da39e509"
}
]
}
]
}
使用 questionIds 我获取另一个 recoed 并将该响应放入现有对象中,如下所示:
{
"status": true,
"data": [
{
"_id": "5e3c1b683ac31f24da39e50a",
"courseName": "Test",
"duration": 1,
"createdBy": "John Die",
"__v": 0,
"updatedAt": "2020-02-06T13:58:00.906Z",
"createdAt": "2020-02-06T13:58:00.906Z",
"isAssigned": false,
"questions": [
[
[
{
"_id": "5e3c1b683ac31f24da39e509",
"index": 1,
"isVideo": false,
"questionType": "MCQ",
"question": "Is this a demo question?",
"title": "Question",
"description": "this is question description",
"link": "",
"createdBy": "Harsh",
"updatedBy": "",
"__v": 0,
"updatedAt": "2020-02-06T13:58:00.521Z",
"createdAt": "2020-02-06T13:58:00.521Z",
"options": [
{
"one": "two"
}
]
}
]
]
],
"questionIds": [
{
"index": 1,
"_id": "5e3c1b683ac31f24da39e509"
}
]
}
]
}
解决方案
async-await
在处理如此复杂的结构时,您应该遵循纯语法。也用于.lean()
将course
from mongoose 对象转换为普通对象。
简化代码:
const course = await Courses.find({}).lean();
const coursePromises = course.map(async key => {
key.questions = [];
const getQuestionsPromises = key.questionIds.map(async ques => {
const question = await Questions.find({ _id: ques._id });
key.questions.push(question);
});
await Promise.all(getQuestionsPromises)
});
await Promise.all(coursePromises)
return res.send({ data: course })
推荐阅读
- python - 在用于数据块的 spark-submit 的主 python 文件中导入其他 python 文件
- java - 如何使用两个包实现观察者模式
- javascript - 如何从缓冲区呈现数据?反应原生 Javascript
- reactjs - redux-presist 不更新浏览器的本地存储
- java - 使用连接 XML 文件连接到 oracle 数据库?
- docker - 可以在 Kubernetes pod 中托管两个 Web 服务吗?
- jquery - 使用ajax请求上传文件后div标签不刷新
- blazor - 单例继续初始化?
- homekit - Apple MFi - Homekit 软件认证
- sql - 机器人不会连接到我们 SQL 服务器上与 AWS 的新连接