Skip to content

Instantly share code, notes, and snippets.

@OzieWest
Created December 31, 2016 09:55
Show Gist options
  • Select an option

  • Save OzieWest/1355b17ff644597b96c4929cd17f10d1 to your computer and use it in GitHub Desktop.

Select an option

Save OzieWest/1355b17ff644597b96c4929cd17f10d1 to your computer and use it in GitHub Desktop.
Async Map  -  A Simple Implementation Without Promises
// asyncMap takes two arguments, a collection of tasks and a callback to run on those tasks
var asyncMap = function (tasks, cb) {
// declare a counter - set it at zero
var counter = 0;
// here we are given tasks as an object
// it's possible tasks is an array
// get number of tasks we need to come back
var numberTask = Object.keys(tasks).length;
// object we will run the final cb on when all tasks have returned
var results = {};
// loop through tasks
for (var key in tasks) {
// why are we wrapping an anonymous function here?
// we don't know when tasks come back
// the key may not be what was originally intended
// creating a function allows us to maintain scope
// this guarantees we pass in the 'key' we want
(function (key) {
// purposely not considering what happens if error returned
// we are defining the callback passed to each task
// tasks[key]() is an invocation of a task that has a predetermined callback
// we are intercepting the result of that callback and something something more with it
tasks[key](function(res) {
// store the result of task in the results storage
results[key] = res;
// increment our counter
counter++
// check if we got all our tasks to comeback
// if so then run our cb passed in to asyncMap
if (counter === numberTask) {
cb(results);
}
})
// invoke our anonymous function with key to create scope
})(key)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment