节点js,等待,直到从MongoDB中获取所有数据

时间:2019-03-07 14:23:31

标签: node.js reactjs mongodb express

我在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时间。但这当然不是一个好主意。有人可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

您应在此代码中使用try catch

getFriendsPosts = async (user,callback) => {
    const arr = [];
    const array = [];
    const db = await MongoClient.connect(url);
    const dbo = db.db("drone-x");
    const results = await dbo.collection("users").find({_id: ObjectId(user.id)})
    const resultPromise =  _.map(results, async element => {
        const friends = _.get(element, 'friends', [])
        if(friends.length != 0) {
        const friendPromise =  _.map(friends, async friend => {
            const ress = await dbo.collection("users").find({_id: ObjectId(friend.id)})
            arr.push(ress);
            const resPromise = _.map(ress, async res => {
             const posts = await dbo.collection("posts").find({userId: res._id.toString()})
                const postPromise =  _.map(posts, post => {
                    array.push(post);
                })
              await Promise.all(postPromise)
            })
           await Promise.all(resPromise)
        })
       await Promise.all(friendPromise)
        } 
    })
   await Promise.all(resultPromise)
    return { arr , array }
}

我不建议这样花费太多时间。您应该使用猫鼬,并对较长的查询使用聚合。