我有一个名为top thread的帖子数组,我正在尝试检索一个数组数组,每个包含原始数组中单个帖子的所有回复的数组都是最好的。这是我获取顶级帖子的代码
exports.topThread = function(req, res){
// gets the leaf id from URL and assigns to OPID
var OPID = req.params.id;
var thread = [];
// finds the post with id OPID from the db
titles.findOne({postID: OPID}, function (err, post) {
if (err) throw err;
getBestThread(OPID, thread, function(result){
branchList.getBranches(function(branches){
// renders content with data retrieved from the post
res.render('content', {title: post.title, content: post.body, OPID: post.postID, currentThread: result, branches: branches});
console.log(result);
});
});
});
};
这部分代码有效:结果是我想要的帖子数组。现在我想将结果数组的每个元素传递给我的getAllOtherReplies函数
//calback to retrieve other replies for a parent comment
getOtherReplies = function(parentID, callback){
postdb.otherReplies(parentID, function(err, commentsArray){
if (err) throw err;
callback(commentsArray);
})
}
getAllOtherReplies = function(threadArray, returnArray, callback) {
async.each(threadArray,
function(value, callback) {
getOtherReplies(value.commentID, function(commentsArray) {
console.log(value.commentID);
if (commentsArray)
returnArray.push(commentsArray);
});
callback();
},
function(err) {
if (err) throw err;
}
);
callback(returnArray);
}
这是postsDB中的函数:
//retrieves other replies from db
exports.otherReplies = function(parentID, callback){
titles.find({type: "comment", parentID: parentID}).sort({hotness: -1}).toArray(function(err, result){
if (err) throw err;
if (result.length > 1)
callback(result.splice(0,1));
else callback(null);
});
};
现在我尝试修改原始代码以调用getAllOtherReplies函数:
exports.topThread = function(req, res){
// gets the leaf id from URL and assigns to OPID
var OPID = req.params.id;
var thread = [];
var allOtherReplies = [];
// finds the post with id OPID from the db
titles.findOne({postID: OPID}, function (err, post) {
if (err) throw err;
getBestThread(OPID, thread, function(result){
getAllOtherReplies(result, allOtherReplies, function(returnArray){
console.log(returnArray);
branchList.getBranches(function(branches){
// renders content with data retrieved from the post
res.render('content', {title: post.title, content: post.body, OPID: post.postID, currentThread: result, branches: branches});
console.log(result);
});
});
});
});
};
而不是为结果中的每个注释返回所有回复的数组数组,它返回一个数组数组,其中每个数组只回复结果中的第一个注释,重复n次,其中n是帖子数结果。我知道我缺少一个异步问题,任何帮助都会受到赞赏。
答案 0 :(得分:1)
在async.each
循环中,getOtherReplies
正在回调中添加commentsArray
,但您在getOtherReplies
之后立即调用异步回调,而不是等待它的回调。
将异步回调移动到getOtherReplies
将是一个良好的开端,可能很好地解决问题。
getOtherReplies(value.commentID, function(commentsArray) {
console.log(value.commentID);
if (commentsArray) {
returnArray.push(commentsArray);
}
callback();
});