Skip to content

Instantly share code, notes, and snippets.

@nitinreddy3
Created October 5, 2018 04:52
Show Gist options
  • Save nitinreddy3/f2c1e6d6e9da38bd8e33280439349e17 to your computer and use it in GitHub Desktop.
Save nitinreddy3/f2c1e6d6e9da38bd8e33280439349e17 to your computer and use it in GitHub Desktop.
asyncAll example
/*
* A simple asyncAll example.
*
* Ignores any error handling and only returns the results to the done callback.
* Each task is expected to take a callback for its first parameter.
*/
// Example call:
asyncAll([doSomething, doSomethingElse], function (results) {
console.log('all done', results);
})
// Using Array.forEach
function asyncAll(tasks, done) {
var count = arr.length;
var results = new Array(count);
tasks.forEach(function(task, i) {
task(function(result) {
results[i] = result;
count -= 1;
if (count === 0) {
done(results);
}
})
})
}
// Using traditional for-loop with var (IIFE)
function asyncAll(tasks, done) {
var count = arr.length;
var results = new Array(count);
for (var i = 0, len = count; i < len; ++i) {
(function (i) {
tasks[i](function(result) {
results[i] = result;
count -= 1;
if (count === 0) {
done(results);
}
})
}(i))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment