我对JS和函数式编程非常陌生,我很难找到一个优雅的解决方案来解决这个问题。本质上,我想向MongoDB服务器发出异步请求,并将结果返回到async to map函数。我遇到的问题是async.map
中的实际函数本身就是异步的。我想在这里知道一个优雅的解决方案,或者至少得到一个指向正确方向的指针!谢谢!
async.map(subQuery,
function(item){
collection.distinct("author", item, function(err, authors){
counter++;
console.log("Finished query: " + counter);
var key = item['subreddit'];
return { key: authors };
})
},
function(err, result){
if (err)
console.log(err);
else{
console.log("Preparing to write to file...");
fs.writeFile("michaAggregate.json", result, function() {
console.log("The file was saved!");
});
}
db.close();
}
);
答案 0 :(得分:1)
只有在获取数据时才应处理项目。只需使用回调即JavaScript的常用方法。像这样:
var processItem = function(item){
// Do some street magic with your data to process it
// Your callback function that will be called when item is processed.
onItemProccessed();
}
async.map(subQuery,
function(item){
collection.distinct("author", item, function(err, authors){
counter++;
console.log("Finished query: " + counter);
var key = item['subreddit'];
processItem(item);
})
},
function(err, result){
if (err)
console.log(err);
else{
// That string added **ADDED**
console.log('HEEY! I done with processing all data so now I can do what I want!');
console.log("Preparing to write to file...");
fs.writeFile("michaAggregate.json", result, function() {
console.log("The file was saved!");
});
}
db.close();
}
);
<强> ADDED 强>
根据async.map
的规范,您可以看到:
https://github.com/caolan/async
async.map(arr, iterator, callback):
callback(err, results) - A callback which is called when all iterator functions have finished, or an error occurs. Results is an array of the transformed items from the arr.
正如您所看到的,回调正是您所需要的!