Created
November 14, 2012 19:58
-
-
Save shesek/4074385 to your computer and use it in GitHub Desktop.
Limit concurrency of async functions
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
# Returns a function that invokes `fn`, with maximum concurrency of `max` | |
# Generalized version of https://gist.github.com/4071443 | |
concurrent = (free, fn) -> | |
queue = [] | |
r = (a..., cb) -> | |
# Queue the call if we have too many running | |
return queue.push [a..., cb] unless free | |
--free | |
fn a..., (resp...) -> | |
++free | |
# Run the next queued request, if we have one | |
r queue.shift()... if queue.length | |
cb resp... | |
# Usage: | |
# To modify an existing function | |
limitedFoo = concurrent 15, foo | |
# And just use `limitedFoo()` like you would normally use `foo()` | |
# Or simply as a decorator | |
foo = concurrent 15, (cb) -> setTimeout cb, 1000 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment