Nodejs for循环并等待,直到循环完成



我有以下代码:

    //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;

我使用nodejs与mongoose和mongodb。我想做的:

  1. 使用mongoose从mongodb获取所有用户
  2. 在lodash的帮助下,每个函数遍历所有用户
  3. 在每个用户上浏览用户书籍(也使用lodash和each)
  4. 如果当前的bookId与函数参数中的bookId匹配-->设置图书"isReading"属性--> true

我的问题是,我只需要回调时,一切都完成了位置#2然后是整个用户。Find及其嵌套回调还没有准备好!

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

我读过一些关于承诺和异步库,但我怎么能在这种情况下使用它?

致以最亲切的问候迈克尔。

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

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
           });

你可以使用同步每个循环从灵活http://caolan.github.io/nimble/

var nimble = require('nimble');
var markAsReading = function (bookId,cb) {
    User.find({}, function (err,users) {
        if(err)
            cb(err);
        nimble.each(users, function (user) {
             nimble.each(user.books, function (book) {
                if(book.matchId === bookId)
                {
                    user.isReading = true;
                }
            });
        });
        cb(null);
    });
};

最新更新