Pau*_*aul 6 javascript postgresql asynchronous node.js sequelize.js
我正在使用Node.js和Sequelize(使用Postgres后端)构建一个网站.我有一个返回许多带有外键的对象的查询,我想传递给外键引用的对象列表.
在示例中,Attendances包含Hackathon密钥,我想返回一个黑客马拉松列表.由于代码是异步的,因此以下内容在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});
});
Run Code Online (Sandbox Code Playgroud)
有没有办法以同步方式进行查询,这意味着我不会返回视图,直到我有"hacks"列表填充所有对象?
谢谢!
使用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
});
})
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6119 次 |
最近记录: |