节点js嵌套循环结果最终推送到单个数组 [英] node js nested loop results finally push to single array

查看:98
本文介绍了节点js嵌套循环结果最终推送到单个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我会得到答案的数组

但是如何获取被回答的用户信息;

but how to get the Answered users info;

该流程为获取帖子列表帖子用户信息帖子用户关注者计数帖子点赞计数 >,登录用户喜欢帖子 True or False 回答回答的用户信息回答的用户关注人数

the flow is Get List of Posts, Post User Info, Post User Followers Count, Post Likes Count, Login User Liked The Post True or False, Answers, Answered User Info and Answered User Followers Count

exports.GetPostList = function(req, res) {
    var SkipCoun = 0;
    SkipCoun = parseInt(req.params.Limit) * 10;
     QuestionsPostModel.QuestionsPostType.find({}, {} , {sort:{createdAt : -1}, skip: SkipCoun, limit: 10  }, function(err, result) {
        if(err) {
            res.status(500).send({status:"False", message: "Some error occurred while Find Following Users ."});
        } else {
                const GetUserData = (result) =>
                    Promise.all(
                        result.map(info => getPostInfo(info))
                    ).then(
                        results => {
                            let [UserInfo, UserFollowers, PostRatingCount, UserRatedCount, AnswersCount, AswersArray ] = 
                            results.reduce(([allOne, allTwo, allThree, allFour, allFive, allSix ], [one, two, three, four, five, six]) => 
                            [allOne.concat([one]), allTwo.concat([two]), allThree.concat([three]), allFour.concat([four]), allFive.concat([five]), allSix.concat([six])], [ [], [], [], [], [], [] ]);
                            res.send({ status: "True", UserInfo: UserInfo, UserFollowers: UserFollowers, PostRatingCount: PostRatingCount, UserRatedCount: UserRatedCount, AnswersCount:AnswersCount, AswersArray:AswersArray })
                        }
                    ).catch(err => res.send({ status: "Fale",Error: err}) );


                const getPostInfo = info =>
                    Promise.all([
                        UserModel.UserType.findOne({'_id': info.UserId }, usersProjection).exec(),
                        FollowModel.FollowUserType.count({'UserId': info.UserId}).exec(),
                        RatingModel.QuestionsRating.count({'PostId': info._id , 'ActiveStates':'Active' }).exec(),
                        RatingModel.QuestionsRating.count({'UserId': req.params.UserId, 'PostId': info._id, 'PostUserId': info.UserId, 'ActiveStates':'Active'}).exec(),
                        AnswerModel.QuestionsAnwer.count({'PostId': info._id , 'ActiveStates':'Active' }).exec(),
                        AnswerModel.QuestionsAnwer.find({ 'PostId':info._id }, 'AnswerText UserId Date' ).exec()
                    ]);

            GetUserData(result);

        }
     });
    };

如何获取结果

推荐答案

传递给Promise.all(). 而您只需要数据.

as you formed the array, and you are passing it inside Promise.all() . and you just need the data.

Promise.all() 文档.

请参见下面的代码(我们可以按承诺.then().catch()进行操作):

see Below Code (we can just do as promise .then() and .catch()):

exports.GetPostList = function (req, res) {
    var SkipCoun = 0;
    SkipCoun = parseInt(req.params.Limit) * 10;
    QuestionsPostModel.QuestionsPostType.find({}, {}, { sort: { createdAt: -1 }, skip: SkipCoun, limit: 10 }, function (err, result) {
        if (err) {
            res.status(500).send({ status: "False", message: "Some error occurred while Find Following Users ." });
        } else {
            const GetUserData = (result) =>
                Promise.all(
                    result.map(info => getPostInfo(info))
                ).then(
                    results => {
                        let [UserInfo, UserFollowers, PostRatingCount, UserRatedCount, AnswersCount, AswersArray] =
                            results.reduce(([allOne, allTwo, allThree, allFour, allFive, allSix], [one, two, three, four, five, six]) =>
                                [allOne.concat([one]), allTwo.concat([two]), allThree.concat([three]), allFour.concat([four]), allFive.concat([five]), allSix.concat([six])], [[], [], [], [], [], []]);
                        res.send({ status: "True", UserInfo: UserInfo, UserFollowers: UserFollowers, PostRatingCount: PostRatingCount, UserRatedCount: UserRatedCount, AnswersCount: AnswersCount, AswersArray: AswersArray })
                    }
                    ).catch(err => res.send({ status: "Fale", Error: err }));


            const getPostInfo = info =>
                Promise.all([
                    UserModel.UserType.findOne({ '_id': info.UserId }, usersProjection).exec(),
                    FollowModel.FollowUserType.count({ 'UserId': info.UserId }).exec(),
                    RatingModel.QuestionsRating.count({ 'PostId': info._id, 'ActiveStates': 'Active' }).exec(),
                    RatingModel.QuestionsRating.count({ 'UserId': req.params.UserId, 'PostId': info._id, 'PostUserId': info.UserId, 'ActiveStates': 'Active' }).exec(),
                    AnswerModel.QuestionsAnwer.count({ 'PostId': info._id, 'ActiveStates': 'Active' }).exec(),
                    AnswerModel.QuestionsAnwer.find({ 'PostId': info._id }, 'AnswerText UserId Date').exec()
                ]).then(data => {
                    let userData = data[0];
                    let followCount = data[1];
                    let ratingCount = data[2];
                    let ratingCountBy_postId = data[3];
                    let answerCount = data[4];
                    let answers = data[5];
                    // now you may need to construct some object or something and pass data as you required.
                    let result = {
                        user: userData,
                        follow_count: followCount,
                        rating_count: ratingCount,
                        rating_countBy_postId: ratingCountBy_postId,
                        answer_count: answerCount,
                        answers: answers
                    };

                }).catch(error => {
                    console.log(error)
                })


                    GetUserData(result);

        }
    });
};

这篇关于节点js嵌套循环结果最终推送到单个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆