Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 600
vp_arth Avatar asked Dec 06 '25 13:12

vp_arth


1 Answers

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);
});
like image 183
robertklep Avatar answered Dec 08 '25 06:12

robertklep



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!