简体   繁体   English

承诺链:父承诺不会等到子承诺被执行

[英]Promise chain: parent promise is not waiting until child promise gets executed

I fetch data from one mongoDB collection, in that response I got Id of another collection's data and fetch that and merge that in one object.我从一个 mongoDB 集合中获取数据,在该响应中,我获得了另一个集合数据的 Id,然后获取并合并到一个对象中。

Here's my code, but it's not wait unitl child primise gets executed.这是我的代码,但不是等待 unitl child primise 被执行。

guide me with my code mistake.指导我解决我的代码错误。

 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 })
          }
        ) 

I got first collection response like this:我得到了这样的第一个集合响应:

{
    "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"
                }
            ]
        }
    ]
}

with questionIds I fetch another recoed and put that reseponse in the existing object like this :使用 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"
                }
            ]
        }
    ]
}

You should follow pure async-await syntax when working with such complex structure.在处理如此复杂的结构时,您应该遵循纯async-await语法。 Also use .lean() to convert the course from mongoose object to a plain object.还可以使用.lean()course从猫鼬对象转换为普通对象。

Simplified code:简化代码:

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 })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM