gpt4 book ai didi

javascript - 同步for循环

转载 作者:行者123 更新时间:2023-12-03 06:11:06 24 4
gpt4 key购买 nike

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循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39315391/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com