如果它们都是承诺,我如何执行几个计数并使用最高计数



下面是我的帖子投票控制器。

如果用户尚未对帖子进行投票(他们的voterId不在votes数组中)。然后,通过将它们的voterId推入支柱的votes阵列来添加它们的vote。然后将voteCount重置为该阵列的length

有一些关于向postAuthor发送通知的附加逻辑,但我省略了该代码,以免混淆问题。

每个post都有一个expiresAt时间戳。每一次投票都会给post更多的生存时间(TTL),但它会给多少时间将取决于帖子属于哪个category。本质上,音乐等更受欢迎的类别的生存时间会比园艺等不太受欢迎的分类少。

所以我需要做的是count有多少userscategory感兴趣。基于此,我可以计算出要添加多少TTL。

问题是,任何帖子都可能有三个类别。不管有多少,我想统计一下最受欢迎的类别。

我该怎么做?我想为post所属的每个类别执行for loop。然后进行计数,与上次计数进行比较,并在必要时进行分配。

当然,这个问题是每个Count都返回一个promise。所以我假设for loop不起作用。

对此有一个合乎逻辑的解决方案吗?谢谢

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);
}

最新更新