I am have a bunch of long running database queries I need to get done before I render a page in node. Each of these queries require a few of their own variables. Is there an easy way to pass variables to the async.parallel() utility in nodejs?
async.parallel([
queryX(callback, A1, A2, A3),
queryX(callback, B1, B2, B3),
queryY(callback, C1, C2, C3),
queryY(callback, D1, D2, D3),
queryZ(callback, E1, E2, E3),
queryZ(callback, F1, F2, F3),
],
function(err, results) { /*Do Render Stuff with Results*/}
);
I am have a bunch of long running database queries I need to get done before I render a page in node. Each of these queries require a few of their own variables. Is there an easy way to pass variables to the async.parallel() utility in nodejs?
async.parallel([
queryX(callback, A1, A2, A3),
queryX(callback, B1, B2, B3),
queryY(callback, C1, C2, C3),
queryY(callback, D1, D2, D3),
queryZ(callback, E1, E2, E3),
queryZ(callback, F1, F2, F3),
],
function(err, results) { /*Do Render Stuff with Results*/}
);
Share
Improve this question
asked Feb 23, 2014 at 18:39
JHAWNJHAWN
3994 silver badges18 bronze badges
1
-
No,
async
does not have helpers for this. You could try.bind()
or similar partial application methods, but your callback being in the first place is odd and might hinder using them. – Bergi Commented Feb 23, 2014 at 18:45
2 Answers
Reset to default 5You should respect the callback as last argument nodejs convention when you write functions. That way you could have use Function.bind to call your functions instead.
var queryx = function(A,B,C,callback){ .... ; callback(err,result) };
async.parallel([queryx.bind(null,A1,B2,A3),...,],callback);
bind returns a partial application :
https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
Is there an easy way to pass variables to the async.parallel() utility in nodejs?
Not in async
itself, you could however write a little helper function for this:
function passWithCallbackFirst(fn) {
var args = [].slice.call(arguments, 1);
return function(cb) {
args.unshift(cb);
return fn.apply(this, args);
};
}
async.parallel([
passWithCallbackFirst(queryX, A1, A2, A3),
passWithCallbackFirst(queryX, B1, B2, B3),
passWithCallbackFirst(queryY, C1, C2, C3),
passWithCallbackFirst(queryY, D1, D2, D3),
passWithCallbackFirst(queryZ, E1, E2, E3),
passWithCallbackFirst(queryZ, F1, F2, F3),
], function(err, results) {
/*Do Render Stuff with Results*/
});