0

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?

3
  • Actually, async.map's only example covers a case that is almost identical to yours. Commented Oct 21, 2012 at 11:58
  • Hmm... Probably I don't get something... what should the signature for iterator be? Should it not return value (like result = GetData(...))? Commented Oct 21, 2012 at 12:19
  • Nevermind. Found a bit more helpful example in this thread . Thanks for the answer. Commented Oct 21, 2012 at 12:23

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

That's perfect! It explains how to get result from asynchronous iterator so much better than async docs. Thank you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.