异步函数在 Async.map 中的恢复结果

Returing result of asynchronous function within Async.map

本文关键字:恢复 结果 map 函数 Async 异步      更新时间:2023-09-26

我对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. 如您所见,回调正是您所需要的!