Nodejs for-loops并等到循环完成
我有以下代码:
//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;
我用mongoose和mongodb使用nodejs。 我想做的事:
- 用mongoose从MongoDB获取所有用户
- 在lodash的帮助下,每个function都经过所有的用户
- 在每个用户上通过用户书籍(也与lodash和每个)
- 如果当前bookId与函数参数 – >设置书籍“isReading”属性 – > true中的bookId相匹配
我的问题是,我只需要callback,当一切都完成了位置#2但是,然后整个User.find和它的嵌套callback没有准备好!
我怎么能解决这个问题,如果所有的循环和查找方法都准备好了,我会做callback?
我已经读过有关承诺和asynchronous库的东西,但我怎么能在这种情况下使用它?
最好的问候迈克尔
我finaly soved与这种模式的asynchronous库这个问题:
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); }); };