同步for循环
Synchronous for loop
MongoClient.connect('mongodb://127.0.0.1:27017/manufacturers',
function(err, db) {
db.listCollections().toArray(function(err, collections) {
for (var key in collections) { // iterate over all collections
var manufacturer = collections[key]['name'];
var query = {}; // and get all documents
findDocuments(db, manufacturer, query, processData);
}
});
});
var findDocuments = function(db, collection, queryObj, callback) {
var cursor = db.collection(collection).find(queryObj);
cursor.each(function(err, docs) {
if (docs != null) { console.log(docs); }
});
}
. .它可以工作,但只能从一个集合中获取数据,而不是所有集合。
似乎for
循环马上结束,我如何使它等到中间函数返回?
For循环同步运行,您需要的是一个函数。我用以下结构创建了一个示例数据库
manufacturers (db)
man1 (collection 1)
man1doc1
man1doc2
man2 (collection 2)
man2doc1
并运行以下代码依次打印所有集合中的所有文档,每次一个集合。
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://127.0.0.1:27017/manufacturers',
function(err, db) {
db.listCollections().toArray(function(err, collections) {
if(!collections.length){
console.log('No collections found');
return;
}
function sequentialIterate(key){
if(key === collections.length){
console.log('All documents in all collections printed');
return;
}
var manufacturer = collections[key]['name'];
var query = {};
db.collection(manufacturer).find(query, function(err, cursor){
cursor.each(function(err, doc){
if(doc){
console.log(doc);
}
else{
console.log('All documents in collection ' + manufacturer + ' printed');
sequentialIterate(key + 1);
}
});
});
};
sequentialIterate(0); // kick things off
});
});
打印以下内容:
{ _id: 57cc44fc03b65f4084865057, name: 'man2doc1' }
All documents in collection man2 printed
{ _id: 57cc44f003b65f4084865055, name: 'man1doc1' }
{ _id: 57cc44f303b65f4084865056, name: 'man1doc2' }
All documents in collection man1 printed
All documents in all collections printed
如果你愿意,你可以用回调来替换console.log()。
相关文章:
- 为什么JavaScript在for循环为3时向所有4发出警报
- 另一个ajax调用中的Jquery ajax调用在for循环中没有按预期工作
- 我的javascript for循环不起作用
- For循环冻结Javascript
- 如何在for循环中添加事件侦听器
- 双“for”循环(循环)
- javascript for循环不起作用
- for循环中的javascript if语句找不到==
- Javascript在for循环中等待处理请求
- 我没有'I don’我不理解for在循环中的用途
- 为什么在 Javascript 中使用空的 for 循环 - for(;;).
- 错误后如何停止循环“FOR”
- 如何使用循环 for 与 java 脚本一起检查输入中的值
- 如何正确使用ngRepeat,同时使用循环for
- 是否可以使用循环(for/while)来制作动画?
- 在循环for循环时如何进入和退出
- Javascript原型循环for in数组
- 在对象数组中循环for
- Javascript循环:for循环工作,但不能映射
- 如何创建一个循环"for"在json