Nodejs for-loops并等到循环结束 [英] Nodejs for-loops and wait until loop finished

查看:98
本文介绍了Nodejs for-loops并等到循环结束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

    //Marks all users which are reading the book with the bookId
 var markAsReading = function (bookId,cb) {
    User.find({}, function (err,users) {
        if(err)
            cb(err);
        //Go through all users with lodash each function
        _(users).each(function (user) {
            //Go through all books
            _(user.books).each(function (book) {

                if(book.matchId === bookId)
                {
                    user.isReading = true;
                    //cb();
                }
            });
        });
        //Need to callback here!!#1 cb(); -->Not working!
    });
       //Or better here! cb() --> Not working
};
exports.markAsReading = markAsReading;

我正在使用带有mongoose和mongodb的nodejs。
我想做什么:

I'am using nodejs with mongoose and mongodb. What i want to do:


  1. 使用mongoose从mongodb获取所有用户

  2. 在lodash的帮助下,每个功能遍历所有用户

  3. 在每个用户上浏览用户书籍(也使用lodash和每个用户)

  4. 如果当前bookId与函数参数中的bookId匹配 - >设置书籍isReading属性 - > true

  1. Get all users from mongodb with mongoose
  2. With the help of the lodash each-function go through all users
  3. On each user go through the users books (also with lodash and each)
  4. if the current bookId matches the bookId in the function parameter --> Set the book "isReading" property -> true

我的问题是我只需要在所有位置完成后回调#2
然后整个User.find及其嵌套回调都没有准备好!

My problem is that i only need to callback when everything is finished on position #2 But then the whole User.find and its nested callbacks are not ready!

怎么能我解决了这个问题,如果所有循环和find方法都准备就绪,我会做回调吗?

How can i solve this that i do the callback if all loops and the find methods are ready?

我已经阅读了有关promises和async lib的内容,但我怎样才能在这个场景?

I have read something about promises and the async lib but how can i use it in this scenario?

最好的问候
Michael

Best Regards Michael

推荐答案

我最终用这种模式用异步库来解决这个问题:

I finaly soved this problem with the async library with this pattern:

async.forEach(list,function (item,callback) {
              //do something with the item
              callback();//Callback when 1 item is finished
           }, function () {
               //This function is called when the whole forEach loop is over
               cb() //--> This is the point where i call the callback because the iteration is over
           });

这篇关于Nodejs for-loops并等到循环结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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