Search code examples
node.jsnode-async

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


I can't to find a method of async.js library for followed:

I have:

  • keys array ['a', 'b', 'c']
  • 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?


Solution

  • 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);
    });