Cat*_*ish 1 javascript asynchronous node.js
我正在尝试解决这个 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();
Run Code Online (Sandbox Code Playgroud)
编辑
这是一个更具体的示例,使用下面的大部分建议进行了更新,但仍然不起作用。
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));
});
}
Run Code Online (Sandbox Code Playgroud)
不使用承诺或任何其他依赖项/库,您可以简单地
function doStuff(callback) {
Run Code Online (Sandbox Code Playgroud)
添加计数器
var cursor = new Array(); // init with some array data
var cursorTasks = cursor.length;
function cursorTaskComplete()
{
cursorTasks--;
if ( cursorTasks <= 0 ) {
// this gets get called after each task reported to be complete
callback();
}
}
for ( var i = 0; i < cursor.length; i++ ) {
...doing stuff here takes some time and does some async stuff
Run Code Online (Sandbox Code Playgroud)
每次异步请求后检查
...when async operation is complete call
cursorTaskComplete()
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
22366 次 |
最近记录: |