【问题标题】:Nodejs for-loops and wait until loop finishedNodejs for循环并等待循环完成
【发布时间】:2014-07-19 02:03:12
【问题描述】:

我有以下代码:

    //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 完成所有操作时回调 但是整个 User.find 及其嵌套的回调还没有准备好!

如果所有循环和查找方法都准备好,我该如何解决这个问题?

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

最好的问候 迈克尔

【问题讨论】:

  • 哪一行 //cb();意思是 ?它是评论还是你在这里回调?回调只能使用一次
  • 测试async npm 模块,它有很多方便的实用功能。 eacheachSeries,就是其中两个。

标签: javascript node.js mongoose


【解决方案1】:

您可以从灵活的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);
    });
};

【讨论】:

  • 我尝试过灵活但没有用!在循环结束之前执行回调!
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-30
    相关资源
    最近更新 更多