从循环中的数据库中获取异步结果

时间:2015-10-01 07:58:13

标签: javascript angularjs node.js asynchronous express

首先,我必须从数据库中获取帖子然后循环通过它以获取其评论,然后我必须遍历每个评论以使其喜欢!这里现在我面临问题,因为我从数据库中获取喜欢异步!有没有办法,我可以等到每个数据库记录被提取,然后我可以响应数据?

这是我的代码

  attachCommentsLikes: function(req, res, next) {
            if(req.cdata.success === 0) return next();

            var cmnt = _.pluck(req.cdata.message.data, 'comments');
            var postsComment = [];
            _.forEach(cmnt, function(item, index) {
                postsComment[index] = _.pluck(item, 'id');
            });

            async.forEachOf(postsComment, function(item, index, cb) {
                anydb(req.user.database, 'discussion_comments_likes').inn({
                    data: item,
                    where: "comment_id"
                }, function(error, result) {

                    item.forEach(function(commentId, indexOfCommentId) {

                        var likes = _.where(result, {
                            comment_id: commentId,
                            status: 1
                        }).length;
                        req.cdata.message.data.forEach(function(current, indexOfPosts) {
                            var indexOfComment = _.findIndex(current.comments, function(chr) {
                                return chr.id === commentId;
                            });
                            if (indexOfComment != -1) {
                                req.cdata.message.data[indexOfPosts].comments[indexOfComment].likes = likes;
                                if (_.where(result, {
                                    comment_id: commentId,
                                    status: 1,
                                    liked_by: req.user.id
                                }).length) {
                                    req.cdata.message.data[indexOfPosts].comments[indexOfComment].liked = 1;
                                }
                            }
                        });


                    });

                    if ((postsComment.length - 1) === index) {
                        console.log(req.cdata.message.data)
                        next();
                    }
                });

            }, function(item) {

            });
            // next();
        },

更新:我解决了这个问题,方法是将一个数组中的所有注释id连接起来并获取一个查询,而不是使用sql函数中的每个id循环

var allIds = [];
            _.forEach(postsComment, function(item, index) {
                _.forEach(item, function(current) {
                    allIds.push(current);
                });
            });

0 个答案:

没有答案