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*/}
);
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).
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With