【发布时间】:2019-03-11 21:39:44
【问题描述】:
我在 Node js 中遇到了异步函数和回调的问题。我需要获取我朋友的所有帖子并显示它。但是如果我在没有 setTimeout() 的情况下这样做,它只会返回部分数据。我如何在不设置 setTimeout 的情况下解决这个问题?当然,等待 5-6 或 10 秒来获取所有数据是很荒谬的。我也尝试过 Promises,但再次响应不完整。请问有人可以帮助我吗?
//Sending request with axios to Controller
axios.post(packages.proxy+'users/getFriendsPosts',{id: user_id},config)
.then(res => {
// Code for displaying result
})
//User Controller
router.post("/getFriendsPosts", getFriendsPosts);
//Send request body to userService.js
function getFriendsPosts(req, res, next) {
userService.getFriendsPosts(req.body, function(posts, user){
res.json({posts,user});
})
.catch(err => next(err));
}
//userService.js
module.exports = {
getFriendsPosts,
};
async function getFriendsPosts(user,callback){
var arr = [];
var array = [];
MongoClient.connect(url, async function(errr, db) {
if (errr) throw errr;
var dbo = db.db("drone-x");
//Find user
dbo.collection("users").find({_id: ObjectId(user.id)}).toArray(async function(err, result) {
if (err) throw err;
result.forEach(async function(element, index) {
if(element.friends.length != 0){
element.friends.forEach(async function(elem) {
//Find user's friends
dbo.collection("users").find({_id: ObjectId(elem.id)}).toArray(async function(error, res) {
if (error) throw error;
//push user's friends to arr
arr.push(res);
res.forEach(async function(elements) {
//Find user's friends posts
dbo.collection("posts").find({userId: elements._id.toString()}).toArray(async function(errors, results) {
if (errors) throw errors;
//push user's friends posts to array
array.push(results);
//callback results through setTimeout
setTimeout(async function(){ await callback(array, arr); db.close(); }, 2000);
});
});
});
});
}
else
{
await callback("0");
}
});
});
});
}
如果我不使用 setTimeout 函数,它只会返回 2-3 个数据,但使用 setTimeout,它会返回所有数据。如果数据会增加,那么我需要增加 setTimeout 时间。但这当然不是好主意。有人可以帮助我吗?
【问题讨论】:
-
承诺解决你的问题,但是这个庞大的查询需要太多时间。使用猫鼬或聚合来整理一点时间和速度。
-
@AshokPatidar 我尝试了 Promise,但它再次返回不完整的数据
标签: node.js reactjs mongodb express