Reputation: 46
I have this route in a social media that I'm building that loops through all the users your are following and gets their posts. I am using await and .exec() but the output I am getting is a pending promise.
Route:
router.get("/following", auth, async (req, res) => {
try {
const user = await User.findOne({ firebaseUID: req.authId });
const posts = await user.following.map(async (usr) => {
await Post.find({ userID: usr.user }).exec();
});
console.log(posts);
res.json(posts);
} catch (err) {
console.error(err.message);
res.status(500).send("Server Error");
}
});
The output I am getting from this is [ Promise { <pending> }, Promise { <pending> } ]
.
I am unsure why the promise is not being resolved when I am using await in an asynchronous function and .exec()?
Upvotes: 0
Views: 43
Reputation: 224
That's because you're calling an async method inside map
, and map
doesn't wait for the promise to get resolved, but you can use a for
loop instead.
let posts = []
for(let i=0; i<user.following.length; i++) {
posts.push(
await Post.find({userID: user.following[i].usr }).exec()
);
});
console.log(posts);
Upvotes: 1