Skip to content

Instantly share code, notes, and snippets.

@lucnap
Last active May 3, 2016 16:29
Show Gist options
  • Save lucnap/a5f1e470f0280a80392b98eacdb2866a to your computer and use it in GitHub Desktop.
Save lucnap/a5f1e470f0280a80392b98eacdb2866a to your computer and use it in GitHub Desktop.
Javascript Nodejs execute function in async parallel with arguments
/*
the trick is in function.bind(null, args ...)
The functions will be executed independently but the results will be returned all togheter
in the array in the same order the functions were called
*/
var async = require("async");
function fn1(paramA, paramB, paramC, callback) {
setTimeout(function(){
var ret = '(' + paramA + ' ' + paramB + ' ' + paramC + ')';
callback(null, ret); // err, result
}, 350);
}
function fn2(paramA, paramB, paramC, callback){
setTimeout(function(){
var ret = '(' + paramA + ' ' + paramB + ' ' + paramC + ')';
callback(null, ret); // err, result
}, 100);
}
async.parallel([fn1.bind(null, 'a', 'b', 'c'), fn2.bind(null, 'A', 'B', 'C')], function(err, result) {
console.log(result);
});
// with series functions are executed one after the other in the sequence provided
async.series([fn1.bind(null, 'a', 'b', 'c'), fn2.bind(null, 'A', 'B', 'C')], function(err, result) {
console.log(result);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment