Paulo Oliveira
Paulo Oliveira

Reputation: 2384

How to invoke async.map function with an iterator with multiple arguments?

I have this function:

_get(url, param, function(err, body, res) {
  /* do something */
});

I need to execute this function several times where param takes different values each iteration. (param comes from an array)

So, I decided to try with async.map as stated on the documentation has this definition:

map(arr, iterator, [callback])

Where iterator needs to be something like iterator(item, callback) So, at this moment I see that my function it's not compatible, so for that matter I tried to resolve like this

var fn = function(param, callback) {
  return _get(url, param, callback);
};

And when I executed with async.map I expected to get the merged results like this

async.map(scope, fn, function(err, results) {
  /* handle results */
});

But results returns undefined. I suspect because the return inside fn which misleads async.map.

What should I change/correct here?

Upvotes: 0

Views: 1079

Answers (1)

caasjj
caasjj

Reputation: 1363

That return won't have any effect on async.map. I think the problem is with the signature of the callback. Assuming scope is the array where you have your param values, the following should run your function over those values and provide an array in results - assuming _get calls its anonymous callback with no error:

async.map(scope, function(param, cb) {

   _get(url, param, function(err, body, res) {
       if (err) return cb(err);
       /* do something */
       cb(null, /* whatever you want to pass on to final callback */);
   })
},
function(err, result) {
   if (err) // handle err

   // result is array of values from _get's callback
})

Upvotes: 1

Related Questions