我正在使用co
运行一个生成器函数来执行一些抓取和清理数据。但是,我在循环后从未到达代码的某个部分。这是我的代码的样子:
function*(){
var url = "mongodb://" + config.host + ":" + config.port + "/" + config.db;
var db = yield MongoClient.connect( url );
for( var establishment in [ {"establishment_id": 16} ] ){
var establishment_type = establishment.id;
var response = yield getRestaurants( establishment_type );
var restaurants = JSON.parse( response.body ).restaurants;
// here we create our restaurants in "saveable" form
var saveableRestaurants = [];
for(var i = 0; i < restaurants.length; i++){
var saveableRestaurant = restaurants[i].restaurant;
saveableRestaurant._id = restaurants[i].restaurant.R.res_id;
// Remove unwanted fields
//... code removed for brevity ...
// convert cuisine string into its appropriate id form
var cuisines = saveableRestaurant.cuisines.split(",");
var ids = [];
for( var i = 0; i < cuisines.length; i++ ){
console.log("LOOKING UP ID FOR ", cuisines[i]);
var match = yield db.collection(CUI).findOne({"cuisine_name":cuisines[i].trim()});
console.log("ID FOR ", cuisines[i], " IS", match.cuisine_id);
ids.push( id );
}
// I NEVER REACH THIS LINE!!!!
console.log( "ALL IDS ", ids );
}
}
db.close();
}
我从未在功能结束时到达控制台声明
答案 0 :(得分:1)
很可能是您没有注意到异步异常。你应该使用
function*() {
var url = "mongodb://" + config.host + ":" + config.port + "/" + config.db;
var db = yield MongoClient.connect( url );
try {
for (var establishment of [ {"establishment_id": 16} ]) {
var establishment_type = establishment.id;
var response = yield getRestaurants( establishment_type );
var restaurants = JSON.parse( response.body ).restaurants;
// here we create our restaurants in "saveable" form
var saveableRestaurants = [];
for (var i = 0; i < restaurants.length; i++) {
var saveableRestaurant = restaurants[i].restaurant;
saveableRestaurant._id = restaurants[i].restaurant.R.res_id;
// Remove unwanted fields
//... code removed for brevity ...
// convert cuisine string into its appropriate id form
var cuisines = saveableRestaurant.cuisines.split(",");
var ids = [];
for (var i = 0; i < cuisines.length; i++) {
console.log("LOOKING UP ID FOR ", cuisines[i]);
var match = yield db.collection(CUI).findOne({"cuisine_name":cuisines[i].trim()});
console.log("ID FOR ", cuisines[i], " IS", match.cuisine_id);
ids.push( id );
}
console.log( "ALL IDS ", ids );
}
}
} finally {
db.close();
}
}
另外,请不要忘记在.catch(e => console.error(e))
返回的承诺上加co
。
答案 1 :(得分:0)
在浏览MongoDB文档后,我找到了解决方案:
var matches = db.collection( CUI ).find({"cuisine_name" : { "$in" : cuisines }});
while( yield matches.hasNext() ){
var match = yield matches.next();
ids.push( match.cuisine_id );
}
答案 2 :(得分:-1)
您正在打开数据库连接,并且您正尝试使用数据库连接进行操作,因此您可以尝试使用async.each,在完成每项功能后,您可以关闭连接,我看到这就是问题所在。