首页 > 解决方案 > 将从数据库返回的数据存储到nodejs express中的变量中

问题描述

我想根据主题代码获取主题内容,然后在每个主题内容中,我也想获取其子内容,然后将主要内容和子内容作为对象存储在一个数组中并返回数据以做出反应。

请帮我解决一下这个。

节点快递 API 代码

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

标签: node.jsreactjssql-serverexpress

解决方案


问题是当 res.json(Contiants); 执行时,承诺(getCoursesSubContent)尚未解决。

您需要像 jax-p 所说的那样使用 await 。另请注意,您不能将 forEach 与 await/promises 一起使用(当然可以,但它不会像您希望的那样工作: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);
    }
});

推荐阅读