Node.js for循环,等到循环结束

rub*_*bik 2 javascript mongoose node.js

我有以下代码:

    //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;
Run Code Online (Sandbox Code Playgroud)

我正在将nodejs与mongoose和mongodb一起使用。我想做的事:

  1. 使用mongoose从mongodb获取所有用户
  2. 在lodash的帮助下,每个功能都遍及所有用户
  3. 在每个用户上浏览用户书籍(也包括lodash和每个书)
  4. 如果当前bookId与功能参数中的bookId相匹配->设置书籍“ isReading”属性-> true

我的问题是,仅当位置2上的所有操作都完成时,我才需要回调,但是整个User.find及其嵌套的回调尚未准备好!

如果所有循环和find方法都准备好了,我该如何解决回调问题?

我已经阅读了有关Promise和异步lib的内容,但是在这种情况下如何使用它呢?

最好的问候迈克尔

rub*_*bik 5

我最终使用以下模式解决了异步库的此问题:

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
           });
Run Code Online (Sandbox Code Playgroud)