Possible Duplicate:
Cannot use “map” function within async module
I've got a problem like this:
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, ...]
I can imagine why it happens (return tempResult
fires before the async function returned any data - it's slow after all), but can't quite see how to make it right.
My guess is async.map might help, but I fail to see how right away.
Maybe someone more experienced in asynchronous programming might explain the way?
You could try something like:
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
});
As you can see, you'll need to shift the code that processes the results into the function to be passed into async.map
.