【发布时间】:2021-03-13 04:29:59
【问题描述】:
我想获取当前用户的所有帖子和他朋友的所有帖子。该代码正在运行,但我对同时使用 async-await 和 Promise.all 感到困惑。当我一起使用它们时应该如何处理错误以及使用嵌套异步函数的最佳方法是什么?提前致谢。
router.get("/timeline", verify, async(req, res, next) => {
let postArray = [];
try {
const posts = await Post.find({
userId: req.user.id
});
postArray.push(...posts);
const currentUser = await User.findById(req.user.id);
const promises = currentUser.friends.map(async(friendId) => {
const posts = await Post.find({
userId: friendId
});
posts.map((p) => postArray.push(p));
});
await Promise.all(promises).then(() => res.send(postArray));
} catch (err) {
next(err);
}
});
verify 中间件由 JWT 验证器提供。我的模型是这样的:
const UserSchema = new mongoose.Schema(
{
username: {
type: String,
required: true,
min: 3,
max: 20,
unique: true,
},
email: {
type: String,
required: true,
max: 50,
unique: true,
},
password: {
type: String,
required: true,
min: 6,
max: 1024,
},
profilePicture: {
type: String,
default: "",
},
coverPicture: {
type: String,
default: "",
},
isAdmin: {
type: Boolean,
default: false,
},
friends: {
type: Array,
default: [],
},
},
{ timestamps: true }
);
const PostSchema = new mongoose.Schema(
{
userId: {
type: String,
required: true,
},
desc: {
type: String,
max: 500
},
img: {
type: String,
},
likes: {
type: Array,
default: [],
},
},
{ timestamps: true }
);
【问题讨论】:
标签: javascript node.js mongoose