forEach中有个异步函数,如何等异步函数执行完毕之后再执行整个函数的callback
发布于 11 年前 作者 yaoyuxing03 6065 次浏览 最后一次编辑是 8 年前
exports.getComments=function(query,skip,limit,callback){
Comment.find(query).sort({create_time:-1}).skip(skip).limit(limit).exec(function(error,comments){
    if(error){
        callback(error,null);
    }
    comments.foreach(function(index,comment){
        Comment.find({reply_ID:comment.comment_ID}, function(err, replys){
            comment.reply=replys;
        });
    });
    callback(error,comments);
}) 

我的想法是将comment增加一个reply属性,然后再返回comments集合,但由于Comment.find是异步的,故向各位大虾求助,提供点解决方案的,初学,求照顾

9 回复

谢谢你的回答,但这样的话貌似会触发N次callback

我的解决思路:

 Comment.find(query).sort({create_time:-1}).skip(skip).limit(limit).exec(function(error,comments){
    if (comments.length === 0) {
        return callback(error, []);
    }
    var proxy = new EventProxy();
    var done = function () {
        return callback(error, comments);
    };
    proxy.after('reply', comments.length, done);
    comments.forEach(function(comment,index){
        Comment.find({reply_ID:comment.comment_ID},function(error,replys){
            comment.reply=replys;
            proxy.trigger('reply',replys);
        })
    })
});  

感觉应该可以吧

那你能不能说一下你这段代码到底是什意思?比如comment 是什么。 我们才能给你答案。没头没尾的贴出代码谁能看懂。

not tested, might work:

var ln = comments.length
comments.foreach(function(index, comment) {
     Comment.find({ reply_ID: comment.comment_ID}, function(err, replys) {
        comment.reply = replys;
        ln --
        if (ln === 0) {
           callback(null, comments);
        }
     });
  });'

@saighost 嗯,好来,正在看

这种方式我试过了,貌似不行,我用EventProxy解决了,参考了一下咱们论坛的源码

我这个就是一个评论,回复模块,就像咱们现在这个club一样,你评论就是comment,我再回复你就是reply,关联id就是reply_id=comment_id,评论和回复都放在了同一个表里面

为何不写在存储过程里

MongoDB的存储过程还真不清楚

回到顶部