My Code looks as follows:
const router = require("express").Router();
const Post = require("../models/Post");
const User = require("../models/User");
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 });
})
)
console.log(friendPosts);
res.status(200).json(userPosts.concat(friendPosts))
} catch (err) {
res.status(500).json(err);
}
});
module.exports = router;
When I remove the const friendPosts and the call for the promise and just return the userPosts it works fine and I'm struggling to see how the promise is not resolving.
CodePudding user response:
You might need to define it as async function
Try this:
const friendPosts = await Promise.all(
currentUser.followings.map(async (friendId) => {
const post = await Post.find({ userId: friendId });
return post;
})
)
CodePudding user response:
The problem is with the map inner function , you should make that function to an async
one and inside to await
for that Post.find
.
const friendPosts = await Promise.all(
currentUser.followings.map(async friendId => {
return await Post.find({ userId: friendId });
})
)
CodePudding user response:
The map
function of friendPosts
isn't returning promise. You should make the function async and return promise Post
const friendPosts = await Promise.all(
currentUser.followings.map(async (friendId) => await Post.find({ userId: friendId }))
);