0

I want to fetch subject Contents based on subject code and then inside each subject content, I want to fetch its sub contents as well and then store the main contents and sub contents in one array as object and return the data to react.

Please help me with this.

Node express API code

app.post('/api/teacher/courses/maintopics', (req, res) =>
{
    let SubCode = req.body.data;
    let teacher = new Teacher();
    teacher.getCoursesMainContent(SubCode).then(result =>
    {
        let Contiants = [];
        result.forEach(element =>
        {
            SubContent = [];
            element.forEach(e =>
            {
                let contentCode = e.ContentCode;
                teacher.getCoursesSubContent(contentCode).then()
                .then(res => {
                         SubContent.push(res)
                         // here I want to store the sub content inside SubContent array
                         });
            })
        });
        res.json(Contiants);
    });
});
Dale K
  • 25,246
  • 15
  • 42
  • 71
Belal
  • 13
  • 8
  • 1
    Why there are `then()` two times after `getCoursesSubContent()`? Is it typo or chained promise? Anyway function in `.post()` can be `async (req, res) =>` then you can `await` for `getCoursesSubContent()`. – Jax-p Jun 22 '21 at 11:02

1 Answers1

0

the problem is that when res.json(Contiants); is executed, the promises (getCoursesSubContent) are not resolved yet.

you need to use await like jax-p said. also note that you cannot use forEach with await/promises (well you can, but it wont work as you wish it does : Using async/await with a forEach loop)

app.post('/api/teacher/courses/maintopics', async (req, res, next) =>
{
    try {
       let SubCode = req.body.data;
       let teacher = new Teacher();
       const results = await teacher.getCoursesMainContent(SubCode);
       let Contiants = [];
       for (let element of results) {
           SubContent = [];
           for (let e of element) {
                let contentCode = e.ContentCode;
                
                let res = await teacher.getCoursesSubContent(contentCode);
                SubContent.push(res)
           }
      }
       res.json(Contiants);
    } catch(err) {
      next(err);
    }
});
Raphael PICCOLO
  • 2,095
  • 1
  • 12
  • 18