Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/382.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在Async.map中返回异步函数的结果_Javascript_Async.js - Fatal编程技术网

Javascript 在Async.map中返回异步函数的结果

Javascript 在Async.map中返回异步函数的结果,javascript,async.js,Javascript,Async.js,我对JS和函数式编程非常陌生,我正在努力找到一个优雅的解决方案来解决这个问题。本质上,我希望向MongoDB服务器发出异步请求,并将结果返回给async to map函数。我遇到的问题是async.map中的实际函数本身是异步的。我想知道一个优雅的解决方案,或者至少得到一个指向正确方向的指针!谢谢 async.map(subQuery, function(item){ collection.distinct("author", item, function(err, au

我对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();
    }
  );

您应该仅在提取数据时处理项。只需使用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
的规范,您可以看到:

async.map(arr、迭代器、回调):


callback(err,results)-当所有迭代器函数完成或发生错误时调用的回调。结果是来自arr的转换项数组。
正如您所看到的,回调正是您所需要的

嗯。在这种情况下,一旦我处理了所有的事情,我将如何做一些事情呢?在
processItem()
的末尾,只需调用您需要的函数,该函数将调用n次,对吗?我只想说一次。