如何在另一个asynchronous`each`方法(NodeJS)内部进行asynchronous方法调用?

如何在另一个asynchronous方法中调用asynchronous方法(NodeJS)?

具体的例子 – 使用数据库,我需要删除所有logging。 但是我不能只删掉整个集合,我需要逐一销毁每个logging,在删除之前我需要读取logging,在应用程序中执行一些业务逻辑,然后删除它。

所以,让我们尝试实现我们的deleteAll方法(实际上它是一个来自node-mongodb-native驱动程序的真实API):

 deleteAll = function(selector, callback){ collection.find(selector).each(function(err, doc){ if(err){ callback(err) }else{ if(doc === null){ // each returns null when there's no more documents, we are finished. callback(null) }else{ doSomeBusinessLogicBeforeDelete(doc) // How to delete it using asynchronous `remove` method? collection.remove({_id: doc._id}, function(err){ // What to do with this callback? // And how to make `each` wait untill we // deleting this record? ??? }) } } }) } 

实际上有一种方法 – 使用collection.nextObject方法,而不是collection.each ,但我想知道这是可能的解决这个使用each或不? 现在我相信这是不可能的,但也许我错了?

更新: each方法的来源:

 Cursor.prototype.each = function(callback) { var self = this; if (!callback) { throw new Error('callback is mandatory'); } if(this.state != Cursor.CLOSED) { process.nextTick(function(){ // Fetch the next object until there is no more objects self.nextObject(function(err, item) { if(err != null) return callback(err, null); if(item != null) { callback(null, item); self.each(callback); } else { // Close the cursor if done self.state = Cursor.CLOSED; callback(err, null); } item = null; }); }); } else { callback(new Error("Cursor is closed"), null); } }; 

尝试这样的事情。

 deleteAll = function(selector, callback){ // count all documents you need to fire remove for var count = collection.filter(function(doc) { return doc === null }).length, i = count; collection.find(selector).each(function(err, doc){ if(err){ callback(err) }else{ if(doc === null){ callback(null) }else{ doSomeBusinessLogicBeforeDelete(doc) collection.remove({_id: doc._id}, function(err){ i--; if (i <= 0) callback('done'); }) } } }) } 

所以,在节点几个月后,我得到了我的问题的答案,这里有一个可能的asynchronous实现(可能有其他类似的,但在error handling上有细微的差异):

 asyncEach( function(obj, next){ // do something with obj // call next when You finish and want next object, // You can also pass error into next in case of error. console.log(obj) next() }, function(err){ // Will be called when there's no more objects. } ) 

mongo中的each实现是不同的,它不可能做适当的顺序迭代(也许没关系,也许他们有不同的devise目标)。

那么你写的会起作用,虽然不知道这一行:

  if(doc === null){ // each returns null when there's no more documents, we are finished. callback(null) 

因为,我不知道这个逻辑,但是这个工作。 从技术angular度来说,函数不会等待,只是传递另一个函数,当工作完成时会执行这个函数。 这里所做的是asynchronous和平行的。 你也可以看看asynchronous模块中的每个asynchronous版本和其他一些function。