我正在制作类似社交媒体的网站,用户可以互相关注。在我的一条路线中,我想遍历当前用户,紧跟着是ID数组的数组,找到这些用户的帖子并将其添加到一个大数组中,然后按日期对帖子进行排序。问题是在将帖子添加到客户端之前,该数组已发送到客户端。不知道我是否需要某种异步功能或什么。
我获得帖子的路线
const express = require('express')
const user = require("../models/user')
const router = express.Router()
router.get("/api/:username/following/posts", (req, res) => {
let following = [...req.user.following, req.user._id]
let posts = [], i;
for(i = 0; i < following.length; i++){
User.findById(following[i]).populate("posts")
.then(user => {
for(let b = 0; b < user.posts.length; b++){
posts.push(user.posts[b])
}
})
.catch(err => {
console.log(err)
})
}
console.log(posts) // returns []
res.json(posts)
})
答案 0 :(得分:1)
使用异步/等待
router.get("/api/:username/following/posts", async (req, res) => {
const following = [...req.user.following, req.user._id]
const posts = [];
for(let f of following){
const user = await User.findById(f).populate("posts");
posts.push(...user.posts);
}
console.log(posts)
res.json(posts)
})
仅使用承诺
router.get("/api/:username/following/posts", (req, res) => {
const following = [...req.user.following, req.user._id];
Promise.all(following.map(f => User.findBy(f).populate("posts")))
.then(users => {
const posts = users.map(({posts}) => posts).flat();
console.log(posts);
res.json(posts);
});
})
主要区别在于,仅Promise的代码将并行调用User.findBy,而async / await将依次调用它们(不用担心,顺序也保持在promise版本中)< / p>
如果并行调用findBy时出现问题,而您仍然不想使用async / await,则可以这样做:
router.get("/api/:username/following/posts", (req, res) => {
const following = [...req.user.following, req.user._id];
Promise.all(following.reduce((p, f) => p.then(results => User.findBy(f).populate("posts").then(user => [...results, user])), Promise.resolve([])))
.then(users => {
const posts = users.map(({posts}) => posts).flat();
console.log(posts);
res.json(posts);
});
})
答案 1 :(得分:-1)
您可以使用async / await,也可以将res.json调用移至.then