Parallel multi-tasking
suggest changeasync.parallel(tasks, afterTasksCallback) runs a set of tasks concurrently and waits until every task has finished (each task reports that by calling its callback). The tasks overlap on the event loop. They do not each get a thread.
When the tasks have finished, async calls the main callback with any error and the results.
function shortTimeFunction(callback) {
setTimeout(function() {
callback(null, 'resultOfShortTime');
}, 200);
}
function mediumTimeFunction(callback) {
setTimeout(function() {
callback(null, 'resultOfMediumTime');
}, 500);
}
function longTimeFunction(callback) {
setTimeout(function() {
callback(null, 'resultOfLongTime');
}, 1000);
}
async.parallel([
shortTimeFunction,
mediumTimeFunction,
longTimeFunction
],
function(err, results) {
if (err) {
return console.error(err);
}
console.log(results);
});
Result : ["resultOfShortTime", "resultOfMediumTime", "resultOfLongTime"].
Call async.parallel() with an object
You can pass an object instead of the tasks array. The results are then an object with the same keys as the tasks, so each result stays labeled.
async.parallel({
short: shortTimeFunction,
medium: mediumTimeFunction,
long: longTimeFunction
},
function(err, results) {
if (err) {
return console.error(err);
}
console.log(results);
});
Result : {short: "resultOfShortTime", medium: "resultOfMediumTime", long: "resultOfLongTime"}.
Resolving multiple values
Each parallel function is passed a callback. This callback can either return an error as the first argument or success values after that. If a callback is passed several success values, these results are returned as an array.
async.parallel({
short: function shortTimeFunction(callback) {
setTimeout(function() {
callback(null, 'resultOfShortTime1', 'resultOfShortTime2');
}, 200);
},
medium: function mediumTimeFunction(callback) {
setTimeout(function() {
callback(null, 'resultOfMediumTime1', 'resultOfMediumTime2');
}, 500);
}
},
function(err, results) {
if (err) {
return console.error(err);
}
console.log(results);
});
Result :
{
short: ["resultOfShortTime1", "resultOfShortTime2"],
medium: ["resultOfMediumTime1", "resultOfMediumTime2"]
}