如何在另一個異步each
方法(NodeJS)內部進行異步方法調用?如何在另一個異步`each`方法(NodeJS)內部進行異步方法調用?
具體示例 - 使用數據庫,我需要刪除所有記錄。 但我不能只刪掉整個集合,我需要逐一銷燬每條記錄,在刪除之前我需要讀取記錄,在應用程序中執行一些業務邏輯,然後刪除它。
所以,讓我們嘗試實現我們deleteAll
方法(實際上它是從節點MongoDB的原生驅動一個真正的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
解決這個問題?現在我相信這是不可能的,但也許我錯了?
UPDATE: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);
}
};
你有'each'方法的源代碼嗎?如果你有這個問題,應該很容易找到你。 – hugomg 2012-01-13 16:54:09