中执行此操作。
我有一个回调的问题。
在我的nodejs应用中,我正在尝试获取MongoDB请求返回的一系列JSON对象。我不知道为什么,但它不会像我想要的那样填充。
我怀疑异步结果/回调的问题。
var fruits = ["Peach", "Banana", "Strawberry"];
var finalTab = [];
fruits.forEach(function(fruit) {
db.collection('mycollection').distinct("column1", {"column2":{$regex :fruit}}, (function(err, result) {
finalTab[fruit] = result;
console.log(result); // -> display the desired content
db.close();
if (err) throw err;
}));
});
console.log(finalTab); // -> []
感谢您的帮助。
编辑:由于我需要我的db.collection ...功能...我试图将这些异步命令添加到队列中,执行并获取回调函数。我认为异步nodejs模块可以提供帮助。
有人可以告诉我如何在foreach((?
行finalTab[fruit] = result;
无济于事,因为fruit
没有索引。您需要在forEach()
中使用索引如下 -
var fruits = ["Peach", "Banana", "Strawberry"];
var finalTab = [];
fruits.forEach(function(fruit, index) {
db.collection('mycollection').distinct("column1", {"column2":{$regex :fruit}}, (function(err, result) {
finalTab[index] = result;
console.log(result); // -> display the desired content
db.close();
if (err) throw err;
}));
});
console.log(finalTab); // -> []