Last active
December 20, 2015 04:39
-
-
Save garbados/6072792 to your computer and use it in GitHub Desktop.
JavaScript "Counter" object for iterating over asynchronous tasks, so you can do something once they're done even if they don't complete in any known order.
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
// calls `cb` after `next()` meets `end` | |
// useful for asynchronous iteration | |
var Counter = function(end, cb){ | |
this._count = 0; | |
this.next = function(){ | |
this._count++; | |
if(this._count === end){ | |
cb(); | |
} | |
} | |
} |
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 counter = Counter(queue.length, function(){ | |
// runs when counter has been called as many times as there are items in queue | |
console.log('Finished!'); | |
}); | |
queue.forEach(function(item){ | |
asynchronous_stuff(function(results){ | |
// handle results | |
counter.next(); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment