Reputation: 3356
I have 3 functions func1(), func2() and func3(). They are independent of each other. I would like to execute these 3 methods in parallel and with a single call back method. is it possible something like this
function parentMethod(){
call ([func1(),func2(), func3()],<callback function>);
}
Callback functionality is optional but can these 3 functions be executed in parallel.
Upvotes: 0
Views: 70
Reputation: 3106
You can also use web workers but it'll be a little more verbose solution. You can check this post: HTML5/JS - Start several webworkers
Upvotes: 0
Reputation: 3811
Adding to the promise answer given, you'll need to "promisify" your functions if they don't already return promises (this demo assumes an error-first callback):
let promises = [func1, func2, func3].map(func => {
return new Promise((resolve, reject) => {
func((err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
})
});
});
Promise.all(promises)
.then((results) => {
let [func1Data, func2Data, func3Data] = results;
})
.catch(err => {
console.log('error!', err);
});
Upvotes: 2
Reputation: 22395
Use a promise chain with Promise.all
Promise.all([func1, func2, func3]).then(values => {
//values from all the functions are in the callback param
});
Upvotes: 3