Sometimes, you want to execute a function in different parameters at the same time.
Using async :
let jobs;
function parallel_function (callback, filter, param1, param2) {
mysql.use('some_db')
.query(
/*some query that uses a filter and other params for WHERE*/,
filter,
callback
)
.end()
}
function generic_callback (err, result) {
if (err) {
return /*something something*/;
}
//do something with the accumulated results.
}
//collection came from some magical land.
jobs = _(collection).reduce( (result, item) => {
result.push(parallel_function.bind(null, item.filter, item.param1, item.param2);
return result;
}, []);
async.parallel(jobs, generic_callback);
Using Promises :
let jobs;
function parallel_function (filter, param1, param2) {
return new Promise ( (resolve, reject) => {
mysql.use('some_db')
.query(
/*some query that uses a filter and other params for WHERE*/,
filter,
(err, result) => {
if (err) {
return reject(err);
}
resolve(result);
}
)
.end();
});
}
jobs = _(collection).reduce( (result, item) => {
result.push(parallel_function(item.filter, item.param1, item.param2));
return result;
}, []);
Promise.all(jobs).then(/* do something with the result here*/);
Notice how Promises avoid the use of "bind" by allowing the function to accept parameters as is.
However, there is more simplicity in using Async by intuition
AND
The callback within the promise is hard to factor out.
Which might mean that using Promise.all() for parallel work might be wrong because it did not eliminate the use of callbacks completely.
How do I correct this?