所以我在经过 for 循环后渲染一个网页,但问题是当我将渲染放入 for 循环中时,同一页面会渲染多次,最终会出现错误:
Cannot set headers after they are sent to the client
^^ 这会使我的应用程序崩溃。
如果我将渲染放在 for 循环之外,则无法提取我正在提取的数据。
router.get('/dashboard', (req, res) =>
{
const roomArr = [];
model.findById(req.session.userLogin._id)
.then((user) =>
{
user.bookedRooms.forEach((eachRoom) =>
{
console.log(eachRoom);
roomModel.findById(eachRoom)
.then((roomInfo) =>
{
console.log(roomInfo);
console.log(`Rooms Array: ${roomArr}`);
roomArr.push(roomInfo);
})
.catch((err) =>
{
console.log(`Could not book rooms: ${err}`);
})
})
res.render('registration/dashboard', {
rooms: roomArr,
ttl: title,
sty: style
})
})
})
^^ 如上面的代码所示,我的目标是在 session 中提取 bookingRooms(array) 的 id,然后检查该 id 是否与房间集合中的 roomsID 匹配。如果这 2 个 ID 匹配,则表示用户已预订房间。
我遇到的问题是我的房间没有被拉动,我认为这可能是因为我的渲染不在我的.then之后。
我想我的主要问题是我的渲染是否必须在我的.then之后??
最佳答案
假设user.bookedRooms
是一个常规的Javascript数组
执行如下操作
router.get('/dashboard', (req, res) =>
model.findById(req.session.userLogin._id)
.then(user => Promise.all(user.bookedRooms.map(eachRoom => roomModel.findById(eachRoom))))
.then(rooms => res.render('registration/dashboard', {
rooms,
ttl: title,
sty: style
}))
.catch(err => console.log(`Could not book rooms: ${err}`))
)
说明:
model.findById(req.session.userLogin._id)
- 执行之前的操作- 对 ... 返回的 Promise 数组使用 Promise.all
user.bookedRooms.map
对于每个eachRoom
返回由 返回的 promise
roomModel.findById(eachRoom)
...到目前为止还好吗?- 一旦所有 promise 得到解决,结果将位于
.then(rooms
) 中的rooms
中 res.render('registration/dashboard',
...等,执行您在代码中执行的操作
我使用rooms
作为结果的名称,以快捷方式
res.render('registration/dashboard', {
rooms: roomsArr,
ttl: title,
sty: style
})
至
res.render('registration/dashboard', {
rooms,
ttl: title,
sty: style
})
关于javascript - 是否可以将渲染函数放入 Express 的 for 循环中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59206997/