Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs: Passing function specific variables to Async.parallel()

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*/}
);
like image 378
JHAWN Avatar asked Feb 23 '14 18:02

JHAWN


People also ask

How do you run async function in parallel?

In order to run multiple async/await calls in parallel, all we need to do is add the calls to an array, and then pass that array as an argument to Promise. all() . Promise. all() will wait for all the provided async calls to be resolved before it carries on(see Conclusion for caveat).

Are async functions parallel?

You can call multiple asynchronous functions without awaiting them. This will execute them in parallel. While doing so, save the returned promises in variables, and await them at some point either individually or using Promise.

Can NodeJS run parallel?

NodeJS is a runtime environment for JavaScript. It's server-side and single threaded. That being said, we want to do things asynchronously and in parallel. Now, Node uses several threads, just one execution thread, and a lot goes into it to make it asynchronous, such as queues and the libuv library.


1 Answers

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

like image 58
mpm Avatar answered Oct 06 '22 01:10

mpm