Reputation: 1001
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:
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
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
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