vp_arth vp_arth - 1 month ago 7
Node.js Question

Nodejs async: How to map keys to key-values?

I can't to find a method of async.js library for followed:
I have some keys array ['a', 'b', 'c']
and I have some iterator like:


function it(item, next){
next(null, item+item);
}


If I use
async.map([1, 5], it, cb)
, I get [2, 10].

How can I get { 1: 2, 5: 10 } in this case?

Answer

Just some variations:

// #1
async.map(keys, function(key, next) {
  someFoo(key, function(err, value) {
    // TODO: handle err, or not.
    next(null, value);
  });
}, function(err, result) {
  var finalresult = {};
  keys.forEach(function(key, i) {
    finalresult[key] = result[i];
  });
  cb(err, finalresult);
});

// #2
async.parallel((function() {
  var actions = {};
  keys.forEach(function(key) {
    actions[key] = function(next) {
      someFoo(key, function(err, value) {
        // TODO: handle err, or not.
        next(null, value);
      });
    };
  });
  return actions;
})(), function(err, results) {
  cb(err, finalresult);
});
Comments