如何在node.js中的映射迭代器中正确执行异步I/O?

如何在node.js中的映射迭代器中正确执行异步I/O?,node.js,asynchronous,map,Node.js,Asynchronous,Map,可能重复: 我遇到了这样的问题: var paths = ['path1', 'path2', 'path3', ...]; //Some arbitrary array of paths var results; //I need to collect an array of results collected from these paths results = paths.map(function(path){ var tempResult; GetData

可能重复:

我遇到了这样的问题:

    var paths = ['path1', 'path2', 'path3', ...]; //Some arbitrary array of paths

    var results; //I need to collect an array of results collected from these paths

results = paths.map(function(path){
  var tempResult;

  GetData(path, function(data){ //Third-party async I/O function which reads data from path
    tempResult = data;
  });

  return tempResult;
});

console.log(results); //returns something like [nothing, nothing, nothing, ...]
我可以想象为什么会发生这种情况(
return tempResult
在异步函数返回任何数据之前触发—毕竟速度很慢),但我不太明白如何正确处理

我的猜测是可能会有帮助,但我没能马上看到效果


也许有更具异步编程经验的人可以解释一下方法?

您可以尝试以下方法:

async.map(paths,function(path,callback){
    GetData(path,function(data){ callback(null,data); });
},function(error,results){
    if(error){ console.log('Error!'); return; }
    console.log(results);
    // do stuff with results
});

正如您所看到的,您需要将处理结果的代码转移到要传递到
async.map

的函数中,实际上,
async.map
的唯一示例涵盖的情况与您的情况几乎相同。嗯。。。也许我没有得到什么。。。迭代器的签名应该是什么?它是否应该不返回值(比如result=GetData(…)?无需担心。找到了一个更有用的例子。谢谢你的回答,太好了!它解释了如何从异步迭代器获得比异步文档更好的结果。非常感谢。