gpt4 book ai didi

javascript - 是否可以将渲染函数放入 Express 的 for 循环中?

转载 作者:行者123 更新时间:2023-12-01 00:23:31 24 4
gpt4 key购买 nike

所以我在经过 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}`))
)

说明:

  1. model.findById(req.session.userLogin._id) - 执行之前的操作
  2. 对 ... 返回的 Promise 数组使用 Promise.all
  3. user.bookedRooms.map 对于每个 eachRoom 返回由
  4. 返回的 promise
  5. roomModel.findById(eachRoom) ...到目前为止还好吗?
  6. 一旦所有 promise 得到解决,结果将位于 .then(rooms) 中的 rooms
  7. 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com