express
を使用してmongoose
でMONGODB
を使っています
下記はフォローしているユーザの投稿と自分の投稿を取得するエンドポイントです
SNSでよくあるタイムラインです。
router.get("/timeline/all", async (req, res) => {
try {
// 自分が投稿した内容
const currentUser = await User.findById(req.body.userId);
const userPosts = await Post.find({ userId: currentUser._id });
// フォローしているユーザーの投稿
const friendPosts = await Promise.all(
currentUser.followings.map((friendId) => {
return Post.find({ userId: friendId });
})
);
return res.status(200).json(userPosts.concat(...friendPosts));
} catch (err) {
res.status(500).json(err);
}
});
フォローしているユーザの投稿で下記の実装をしています。
//フォローしているユーザの投稿
const friendPosts = await Promise.all(
currentUser.followings.map((friendId) => {
return Post.find({ userId: friendId });
})
);
なぜPromise.allが必要なのでしょうか?
下記のようにPromise.allがなしでもfriendPosts
はawaitを使っているので取得できていると思うのですが、
非同期でDBから引っ張ってきたものをmapで回すにはPromise.allの中で行う必要があるのでしょうか??
// フォローしているユーザーの投稿
const friendPosts = currentUser.followings.map((friendId) => {
return Post.find({ userId: friendId });
});
Promise.all
が複数の非同期処理を並列で行うためにあるのは知っているのですが、今回のケースだと、mapを回し終わるまで結果を返さないようにするためでしょうか?