Skip to content

Instantly share code, notes, and snippets.

@robzhu
Last active December 27, 2016 21:04
Show Gist options
  • Select an option

  • Save robzhu/495e5a6a78805b2162adc3470ea939aa to your computer and use it in GitHub Desktop.

Select an option

Save robzhu/495e5a6a78805b2162adc3470ea939aa to your computer and use it in GitHub Desktop.
DispatchQueue for managing request rate against an API call
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