javascript - promise 链: parent promise is not waiting until child promise gets executed

标签 javascript node.js mongodb promise es6-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,我获取另一个重新编码并将该响应放入现有对象中 像这样:

{
    "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 从 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 })

关于javascript - promise 链: parent promise is not waiting until child promise gets executed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60107092/

相关文章:

javascript - 在 Three.js 继承模式中对原型(prototype)使用扩展有什么好处?

javascript - 使用 moment js 进行 DOB 验证

javascript - Webpack - 导入仅包含全局常量的文件

javascript - Sublime 3 包用于 Jade Syntax Highr、Linting、自动完成等

node.js - 发送 post 请求后 Express Router 重定向

javascript - 如何使旋转元素高度为:100% of its parent?

javascript - 为什么我的express.js 无法运行?

javascript - 如何在mongodb中计算总和

MongoDB 远程备份和恢复

node.js - 按 MEAN 中的 ID 显示图像