Created
October 5, 2018 04:52
-
-
Save nitinreddy3/f2c1e6d6e9da38bd8e33280439349e17 to your computer and use it in GitHub Desktop.
asyncAll example
This file contains hidden or 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
/* | |
* 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