下面是我对帖子进行投票的 Controller 。
如果用户尚未对帖子投票(他们的 voterId
不存在于 votes
数组中)。然后,通过将其 voterId
插入帖子的 votes
数组来添加他们的投票
。然后,voteCount
会重置为该数组的length
。
关于向 postAuthor
发送通知还有一些额外的逻辑,但我省略了该代码,以免混淆问题。
每个post
都有一个expiresAt
时间戳。每次投票都会为该帖子提供更多的生存时间 (TTL),但给予多少时间取决于该帖子所属的类别。从本质上讲,较流行的类别(例如音乐)的 TTL 会低于较不流行的类别(例如园艺)的 TTL。
所以我需要做的是计算
有多少用户
对该类别
感兴趣。基于此,我可以计算出要添加多少 TTL。
问题是任何帖子最多可以有三个类别。无论类别有多少,我都想统计一下最受欢迎的类别。
我该怎么做?我正在考虑为 post
所属的每个类别执行 for 循环
。然后进行计数,与上次计数进行比较,并在必要时进行分配。
当然,这样做的问题是每个Count
都会返回一个promise。所以我假设 for 循环
不起作用。
有一个合理的解决方案吗?谢谢
votePost(req, res, next) {
const postId = req.params.id;
const voterId = req.body.voterId;
Post.findById(postId)
.then(post => {
// let followerCount;
// let mostPopularCategoryFollowerCount = 0;
//
// // for (let i = 0; i < post.categories.length; i++) {
// // followerCount = User.count({ interests: { $eq: post.categories[i] } })
// // .then(count => count);
// //
// // if (followerCount > mostPopularCategoryFollowerCount) {
// // mostPopularCategoryFollowerCount = followerCount;
// // }
// // }
if (post.votes.indexOf(voterId) === -1) {
post.votes.push(voterId);
post.voteCount = post.votes.length;
// DO STUFF HERE WITH FOLLOWER COUNT //
post.save()
.then(() => res.send(post));
}
})
.catch(next);
},
最佳答案
这不是一个完整的实现,只是显示了我在评论中的意思:
votePost(req, res, next) {
const postId = req.params.id;
const voterId = req.body.voterId;
Post.findById(postId)
.then(function( post ) {
Promise.all(
post.categories.map(function( category ) {
return User.count({ interests: { $eq: category } });
})
)
.then(function( counts ) {
return counts.reduce(function( highest, next ) {
return highest > next ? highest : next;
}, 0);
})
.then(function( mostPopularCategoryFollowerCount ) {
// do stuff with the count
})
.catch(function( err ) {
// error handling
});
})
.catch(next);
}
关于javascript - 如果它们都是 promise ,我如何执行多次计数并使用最高的计数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42136738/