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一起使用。我想做的事:
我的问题是,仅当位置2上的所有操作都完成时,我才需要回调,但是整个User.find及其嵌套的回调尚未准备好!
如果所有循环和find方法都准备好了,我该如何解决回调问题?
我已经阅读了有关Promise和异步lib的内容,但是在这种情况下如何使用它呢?
最好的问候迈克尔
我最终使用以下模式解决了异步库的此问题:
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)
| 归档时间: |
|
| 查看次数: |
3128 次 |
| 最近记录: |