我是不是與此代碼真的很高興:異步並行與可變參數的回調
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
}));
問題:
我是否在fn.bind(this, err).apply(this, responses);
中正確使用this
?
有沒有一種現有的方法來做到這一點與異步庫?
更新:這是一種不同的方式來實現:
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
使用'.apply',至少要等到ES6可能是你最好的也是唯一的選擇的功能與陣列PARAM轉換爲功能這需要可變參數。 – 2014-09-12 17:14:33