node.js - 将从数据库返回的数据存储到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);
});
});
解决方案
问题是当 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);
}
});
推荐阅读
- python - 无法使用 Windows Ubuntu 应用程序连接到 Docker
- r - 使用数据表将一个函数应用于具有参数值向量的多列
- python - 字典的性能优化更改
- algorithm - n^0.000001 和 log(n) 等的大 O 复杂度比较
- angular - 类型“{}”上不存在角度 8 地图
- python-3.x - 我如何为 MIPS64 平台编译 Python 3.8.2
- jquery - 尝试使用 JQuery 和谷歌标签管理器呈现新的标题标签
- docker - Gitlab CI/CD Deployer SSH 连接超时
- excel - 根据上面单元格中的文本求和
- javascript - AJAX - 在选择输入中更改事件时更改元素的 innerHTML 不起作用