2014-09-12 32 views
1

我是不是與此代碼真的很高興:異步並行與可變參數的回調

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

+0

使用'.apply',至少要等到ES6可能是你最好的也是唯一的選擇的功能與陣列PARAM轉換爲功能這需要可變參數。 – 2014-09-12 17:14:33

回答

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 
})); 
+0

我會將你的實現添加到jsperf。但是,您可以看到現有的jsperf在哪裏進行數組操作,它比'bind(err).apply(results)'慢得多' – 2014-09-12 23:00:23

+0

有趣的是,我在更新的jsperf上獲得了非常零星的結果。儘管你的實現出現在頂端。很好的工作,並感謝您的幫助。我將添加一些測試,並將PR提交到異步庫。 – 2014-09-13 05:08:02

+0

不知道我對變異'響應'數組的感覺如何 – Maroshii 2014-09-14 10:56:26