异步并行与可变参数回调

时间:2014-09-12 17:11:47

标签: javascript async.js

我对这段代码并不满意:

async.parallel([
  getThing1,
  getThing2,
  getThing3
], function(err, responses) {
  next.ifError(err);

  var thing1 = responses[0],
      thing2 = responses[1],
      thing3 = responses[2];

  // business
});

我希望它看起来像这样,需要:

async.parallel([
  getThing1,
  getThing2,
  getThing3
], function(err, thing1, thing2, thing3) {
  next.ifError(err);

  // business
});

这就是我最终的目标:

async.variadic = function(fn) {
  return function(err, responses) {
    return fn.bind(this, err).apply(this, responses);
  }
}

async.parallel([
  getThing1,
  getThing2,
  getThing3
], async.variadic(function(err, thing1, thing2, thing3) {
  next.ifError(err);

  // business
}));

问题:

我是否在this正确使用fn.bind(this, err).apply(this, responses);

是否存在使用异步库执行此操作的方法?


更新:这是完成此任务的另一种方法:

async.variadic = (function() {
  var _async = {};
  _async.prototype = async;
  _async.parallel = function(tasks, callback) {
    return async.parallel(tasks, function(err, responses) {
      return callback.bind(this, err).apply(this, responses);
    });
  };
  return function() {
    return _async;
  };
})();

async.variadic().parallel([
  getThing1,
  getThing2,
  getThing3
], function(err, thing1, thing2, thing3) {
});

I think I like this one most. Is this a good way to accomplish the task?

这是一个有不同想法的jsperf:http://jsperf.com/variadic-async

1 个答案:

答案 0 :(得分:1)

我个人更喜欢第一种方法。 variadic函数对正在发生的事情知之甚少,可以进一步抽象出来:

function variadic(fn) {
  var self = this;
  return function(err, responses) {
    responses.unshift(err);
    return fn.apply(self, responses);
  }
}

async.variadic = variadic.bind(async);

async.parallel([
    function(cb) {
      cb(null,'1')
    },
    function(cb) {
      cb(null,'2')
    },
    function(cb) {
      cb(null,'3')
    },
], async.variadic(function(err, thing1, thing2, thing3) {
    console.log(this);
    console.log(thing1,thing2,thing3);
  // business
}));