我正在建立一个网站使用Node.js和序列化(与Postgres后端)。我有一个查询,它返回许多具有外键的对象,并且我希望将外键引用的对象列表传递给视图。
在本例中,Attendances包含Hackathon键,我希望返回hackathons的列表。由于代码是异步的,因此以下内容在Node中当然不起作用:
models.Attendance.findAll({
where: {
UserId: req.user.id
}
}).then(function (data) {
var hacks = [];
for (var d in data) {
models.Hackathon.findOne({
where: {
id: data[d].id
}
}).then(function (data1) {
hacks.append(data1);
});
}
res.render('dashboard/index.ejs', {title: 'My Hackathons', user: req.user, hacks: hacks});
});
有没有办法以同步的方式进行查询,也就是说,直到"hacks“列表填满了所有的对象,我才会返回视图?
谢谢!
发布于 2016-10-08 12:08:15
使用Promise.all
执行所有查询,然后调用下一个函数。
models.Attendance.findAll({
where: {
UserId: req.user.id
}
}).then(function (data) {
// get an array of the data keys, (not sure if you need to do this)
// it is unclear whether data is an object of users or an array. I assume
// it's an object as you used a `for in` loop
const keys = Object.keys(data)
// map the data keys to [Promise(query), Promise(query), {...}]
const hacks = keys.map((d) => {
return models.Hackathon.findOne({
where: {
id: data[d].id
}
})
})
// user Promise.all to resolve all of the promises asynchronously
Promise.all(hacks)
// this will be called once all promises have resolved so
// you can modify your data. it will be an array of the returned values
.then((users) => {
const [user1, user2, {...}] = users
res.render('dashboard/index.ejs', {
title: 'My Hackathons',
user: req.user,
hacks: users
});
})
});
发布于 2021-04-12 12:07:47
在异步函数中使用for of
models.Attendance.findAll({
where: {
UserId: req.user.id
}
}).then(async (data) => {
let hacks = []
for (const d of data) {
const _hack = await models.Hackathon.findOne({
where: {
id: data[d].id
}
})
hacks = [...hacks, _hack]
}
res.render('dashboard/index.ejs', {title: 'My Hackathons', user: req.user, hacks: hacks})
})
这将等待hacks数组在渲染之前被填满。这应该适用于API端点。
希望这篇文章能帮助任何遇到同样问题的人。
https://stackoverflow.com/questions/39928452
复制相似问题