Skip to content

Instantly share code, notes, and snippets.

@branneman
Last active June 4, 2021 01:19
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save branneman/d3e3d98703aa6e31701a to your computer and use it in GitHub Desktop.
Save branneman/d3e3d98703aa6e31701a to your computer and use it in GitHub Desktop.
Node.js callback style; run multiple async tasks in parallel
var asyncParallel = function(tasks, callback) {
var results = [];
var count = tasks.length;
tasks.forEach(function(task, index) {
task(function(err, data) {
results[index] = data;
if (err) {
callback && callback(err);
callback = null;
}
if (--count === 0 && callback) {
callback(null, results);
}
});
});
};
asyncParallel([
function(cb) {
setTimeout(function() {
cb(null, 'one');
}, 2000);
},
function(cb) {
setTimeout(function() {
cb(null, 'two');
}, 1000);
}
], function(err, results) {
if (err) return console.log(err);
console.log(results);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment