Reputation: 1419
I have one object which contains two different methods
var samp {
m1: func1,
m2: func2
}
Depending on the number of keys I want to call all the three function parallely Now Im using the following code which runs serially.
switch (sampType) {
case "m1":
{
return new func1();
break;
}
case "m2":
{
return new func2();
break;
}
default:
{
}
}
How can I execute all the methods parallely in node.js? Any help on this will be really helpful
Upvotes: 3
Views: 4765
Reputation: 6352
Another elegant way to do this - using "wiring":
var l = new Wire();
func1(l.branch('post'));
func2(l.branch('comments'));
l.success(function(results) { ... });
// result will be object with results: { post: ..., comments: ...}
https://github.com/garmoshka-mo/mo-wire
Upvotes: 1
Reputation: 2841
Try to use Step.js or bacon.js or async.
With bacon.js, you can do things like:
var result = Bacon.fromNodeCallback(func1, parameters).toProperty();
var onemore = Bacon.fromNodeCallback(func2, parameters).toProperty();
Those two functions are going to be executed on parallel. And then you can have a function to use those two vars like this:
var combined = Bacon.combineAsArray(result, onemore);
combined.onValue(function (an_array) {
// do stuff with an_array, which contains result and onemore
});
Upvotes: 1
Reputation: 3081
Check out async.parallel. You would essentially write:
async.parallel( [
function ( callback ) {
// Code
},
function ( callback ) {
// Code
}
], function ( error, results ) {
// Both done
} );
Upvotes: 4