如何在另一个异步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