UpT*_*eek 50 mongodb node.js mongoskin async.js
使用mongoskin,我可以执行这样的查询,它将返回一个游标:
myCollection.find({}, function(err, resultCursor) {
      resultCursor.each(function(err, result) {
      }
}
但是,我想为每个文档调用一些异步函数,并且只有在调用它之后才转到光标上的下一个项目(类似于async.js模块中的eachSeries结构).例如:
myCollection.find({}, function(err, resultCursor) {
      resultCursor.each(function(err, result) {
            externalAsyncFunction(result, function(err) {
               //externalAsyncFunction completed - now want to move to next doc
            });
      }
}  
我怎么能这样做?
谢谢
更新:
我不想使用,toArray()因为这是一个大批量操作,结果可能不会一次性适合内存.
Tim*_*ple 50
如果您不想使用toArray将所有结果加载到内存中,则可以使用以下类似的方法迭代光标.
myCollection.find({}, function(err, resultCursor) {
  function processItem(err, item) {
    if(item === null) {
      return; // All done!
    }
    externalAsyncFunction(item, function(err) {
      resultCursor.nextObject(processItem);
    });
  }
  resultCursor.nextObject(processItem);
}  
小智 49
一种更现代的方法,使用async/ await:
const cursor = db.collection("foo").find({});
while(await cursor.hasNext()) {
  const doc = await cursor.next();
  // process doc here
}
笔记:
async或者代码应该包含在(async function() { ... })()它使用之后await.await new Promise(resolve => setTimeout(resolve, 1000));在while循环结束时添加(暂停1秒)以显示它一个接一个地处理文档.Jay*_*nki 20
从 node.js v10.3 开始,您可以使用异步迭代器
const cursor = db.collection('foo').find({});
for await (const doc of cursor) {
  // do your thing
  // you can even use `await myAsyncOperation()` here
}
Jake Archibald 写了一篇关于异步迭代器的很棒的博客文章,我是在阅读@user993683 的回答后才知道的。
Dap*_*que 10
这适用于使用setImmediate的大型数据集:
var cursor = collection.find({filter...}).cursor();
cursor.nextObject(function fn(err, item) {
    if (err || !item) return;
    setImmediate(fnAction, item, arg1, arg2, function() {
        cursor.nextObject(fn);
    });
});
function fnAction(item, arg1, arg2, callback) {
    // Here you can do whatever you want to do with your item.
    return callback();
}
| 归档时间: | 
 | 
| 查看次数: | 32490 次 | 
| 最近记录: |