Promise.all()没有等待map函数解析



我的代码如下:

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;

当我删除const friendPosts和调用的承诺,只是返回userPosts它工作得很好,我正在努力看到承诺是如何不解决。

您可能需要将其定义为async函数

试试这个:

const friendPosts =  await Promise.all(
currentUser.followings.map(async (friendId) => {
const post = await Post.find({ userId: friendId });
return post;
})
)

问题在于映射内部函数,您应该将该函数设置为async,并将Post.find设置为await

const friendPosts =  await Promise.all(
currentUser.followings.map(async friendId => {
return await Post.find({ userId: friendId });
})
)

friendPostsmap函数不返回promise。你应该让函数异步,并返回承诺Post

const friendPosts =  await Promise.all(
currentUser.followings.map(async (friendId) => await Post.find({ userId: friendId }))
);

最新更新