6

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*/}
);
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. Commented Feb 23, 2014 at 18:45

2 Answers 2

5

You 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.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

Sign up to request clarification or add additional context in comments.

Comments

0

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*/
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.