我正在对Sequelize进行查询,然后想要根据db中的每个用户运行查询。我不知道如何将这个forEach循环转换为Promise,所以我可以在forEach循环结束后执行操作....
users.forEach(user => {
let userHideCount = 0
Comment_List.findAll({
where: {user_id:user}, attributes: ['user_id','cid'], include: [
{model: Comment, attributes: ['verb','created_time']}
],
order: [[ Comment, 'created_time', 'DESC' ]],
})
.then(cl => {
cl.forEach(comment => comment.get({plain:true}).comments[0].verb === 'hide' ? userHideCount++ : null)
hiddenCounts[user] = userHideCount
})
})
或许有更好的方法可以解决这个问题......任何帮助都非常适合!
答案 0 :(得分:1)
使用Promise.all
并将forEach
转换为返回承诺的map
。例如:
var userPromises = users.map(user => {
let userHideCount = 0
return Comment_List.findAll({
where: {user_id:user}, attributes: ['user_id','cid'], include: [
{model: Comment, attributes: ['verb','created_time']}
],
order: [[ Comment, 'created_time', 'DESC' ]],
})
.then(cl => {
cl.forEach(comment => comment.get({plain:true}).comments[0].verb === 'hide' ? userHideCount++ : null)
hiddenCounts[user] = userHideCount
})
})
// Then, sometime later:
Promise.all(userPromises).then(() => {
// Do stuff.
})