node.js - 节点 Js 链接响应
问题描述
我正在尝试在循环中进行 db 调用,并希望将该数据添加到一个对象中,然后将该对象发送给用户,但我在用户端只得到一个空对象。我已经在 javascript NodeJS 中将这个异步响应检查到一个循环中
router.get('/collection', (req, res) => {
const Data = {}
Section.find({})
.then(sections => {
sections.map(section => {
let id = section._id;
Product.find({section: id})
.then(products => {
// console.log(products)
Data[section.title] = {
title: section.title,
routeName: section.title,
id,
items: products
}
console.log(Data)
})
.catch(err => {
return res.status(500).json(err)
})
})
return res.json(data)
})
.catch(err => {
return res.status(500).json(err)
})
})
我希望输出如下: -
{
food : {
items: [...]
},
vegetable: {
items: [...]
}
}
food 和 vegetables 是从数据库调用中获取的键,每个键中的项目从对数据库的单独调用中返回。
解决方案
return res.json(data)
在解决任何映射的 Product-promises 之前执行(也有一个错字,因为您返回data
而不是Data
)。一种方法是映射find
-promises 并Promise.all
在映射的数组上使用。就像是:
router.get('/collection', (req, res) => {
const Data = {}
Section.find({})
.then(sections => {
const sectionProductPromises = sections.map(section => {
let id = section._id;
return Product.find({
section: id
})
.then(products => {
Data[section.title] = {
title: section.title,
routeName: section.title,
id,
items: products
}
});
});
return Promise.all(sectionProductPromises);
})
.then(() => {
res.json(Data)
})
.catch(err => {
res.status(500).json(err)
});
});