Last active
June 4, 2021 01:19
-
-
Save branneman/d3e3d98703aa6e31701a to your computer and use it in GitHub Desktop.
Node.js callback style; run multiple async tasks in parallel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
}); | |
}); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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