rubiktubik
rubiktubik

Reputation: 1001

Nodejs for-loops and wait until loop finished

I have the following code:

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

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

  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

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!

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

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

Best Regards Michael

Upvotes: 2

Views: 4307

Answers (2)

rubiktubik
rubiktubik

Reputation: 1001

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

Upvotes: 5

Nikolay Lukyanchuk
Nikolay Lukyanchuk

Reputation: 874

You can use sync each loop from nimble 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);
    });
};

Upvotes: 0

Related Questions