异步函数在 Async.map 中的恢复结果
Returing result of asynchronous function within Async.map
我对JS和函数式编程非常陌生,正在努力为这个问题找到一个优雅的解决方案。本质上,我想向MongoDB服务器发出异步请求,并将结果返回到异步映射函数。我遇到的问题是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();
}
);
您应该仅在获取数据时处理项目。只需使用回调即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();
}
);
添加
通过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.
如您所见,回调正是您所需要的!
相关文章:
- 奇怪的Javascript结果
- Javascript(jQuery)给了我奇怪的结果
- 为什么不是't窗口.恢复正常工作吗?(javascript/jquery)
- JSONP请求返回结果,但也触发error_callback
- 如何临时暂停浏览器渲染,然后恢复整个页面
- 如何在chrome扩展中存储数据/结果,以及如何使用setTimeout使其只被调用一次
- NodeJS-readline暂停和恢复事件发射器(逐行读取)
- 谷歌地图劫持了iphone's滚动(触摸事件)-如何恢复
- Javascript,输出结果后页面不断刷新
- 这是使用html快照和谷歌获取的预期结果吗?SEO/SPA
- 将地理编码结果转换为php变量以发布到mysql数据库
- AngularJS/HTML/Bootstrap元素用于动态搜索结果
- JQuery:向多个匹配结果添加换行符的最简单方法
- 当查询不在displayField中时,引导Ajax Typeahead不显示结果
- webpack代码拆分了handlerbs文件——结果是文件很大
- JavaScript循环无法正确计算/显示结果
- 相同的RegExp返回不同的结果-第一次是正确的结果,第二次是null
- 异步函数在 Async.map 中的恢复结果
- 筛选/恢复Promise.all结果
- 选择选项背面丢失按钮&搜索结果恢复为默认选项