Last active
December 27, 2016 21:04
-
-
Save robzhu/495e5a6a78805b2162adc3470ea939aa to your computer and use it in GitHub Desktop.
DispatchQueue for managing request rate against an API call
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
| import sleep from 'sleep-promise'; | |
| class DispatchQueue { | |
| constructor(rateLimitInSeconds) { | |
| this.rateLimit = rateLimitInSeconds * 1000; | |
| this.queueSize = 0; | |
| } | |
| async dispatch(call) { | |
| this.queueSize++; | |
| const dispatcher = this; | |
| return new Promise( | |
| async function (resolve, reject) { | |
| await sleep(dispatcher.queueSize * dispatcher.rateLimit); | |
| const result = await call(); | |
| dispatcher.queueSize--; | |
| resolve(result); | |
| } | |
| ) | |
| } | |
| } | |
| async function apiCall() { | |
| await sleep(100); | |
| return 'response'; | |
| } | |
| (async function main() { | |
| var d = new DispatchQueue(1); | |
| for (var i = 0; i < 5; i++) { | |
| // should observe these resolvers will not all be called at once. | |
| d.dispatch(apiCall).then( | |
| function(val) { | |
| console.log(val); | |
| } | |
| ); | |
| } | |
| })(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment