【发布时间】:2014-07-31 16:17:43
【问题描述】:
我正在尝试解决这个 js/async 场景,并且我正在尝试了解其他 js 世界如何处理这个问题。
function doStuff(callback) {
cursor.each(function(err, blahblah) {
...doing stuff here takes some time
});
... Execute this code ONLY after the `cursor.each` loop is finished
callback();
编辑
这是一个更具体的示例,使用以下大多数建议进行了更新,但仍然不起作用。
function doStuff(callback) {
MongoClient.connect(constants.mongoUrl, function(err, db) {
var collection = db.collection('cases2');
var cursor = collection.find();
var promises = []; // array for storing promises
cursor.each(function(err, item) {
console.log('inside each'); // NEVER GETS LOGGED UNLESS I COMMENT OUT THIS LINE: return Q.all(promises).then(callback(null, items));
var def = Q.defer(); // Create deferred object and store
promises.push(def.promise); // Its promise in the array
if(item == null) {
return def.resolve();
}
def.resolve(); // resolve the promise
});
console.log('items'); // ALWAYS GETS CALLED
console.log(items);
// IF I COMMENT THIS LINE OUT COMPLETELY,
// THE LOG STATEMENT INSIDE CURSOR.EACH ACTUALLY GETS LOGGED
return Q.all(promises).then(callback(null, items));
});
}
【问题讨论】:
-
承诺,承诺...
-
@VivinPaliath 我认为这部分无关紧要。我只是遍历 blah 的值并推送到一个数组。
-
我怎么知道我在
cursor.each的最后一个元素。据我所知,没有索引参数mongodb.github.io/node-mongodb-native/api-generated/… -
@Catfish 我会看这里 - github.com/kriskowal/q - 关于如何在继续之前等待多个异步事情完成的大量示例。我认为您在
cursor.each中调用的异步 Mongo API 也能够在每个单独的操作结束时调用回调?
标签: javascript node.js asynchronous