Skip to content

Instantly share code, notes, and snippets.

@trevorhreed
Last active December 14, 2017 21:27
Show Gist options
  • Save trevorhreed/a86bd8e279c140b3153200df130dde7b to your computer and use it in GitHub Desktop.
Save trevorhreed/a86bd8e279c140b3153200df130dde7b to your computer and use it in GitHub Desktop.
Throttles the number of concurrent calls to a promise function
const throttlePromiseFn = module.exports = (fn, { max = 8, PromiseConstructor = Promise } = {}) => {
const queue = [];
let count = 0;
const call = (params, resolve, reject) => {
const promise = fn(...params);
promise.then((value)=>{
checkQueue();
typeof resolve === 'function' && resolve(value);
}).catch((reason)=>{
checkQueue();
typeof reject === 'function' && reject(reason);
});
return promise;
}
const checkQueue = () => {
count--;
const next = queue.pop();
if(next){
count++;
call(next.params, next.resolve, next.reject);
}
}
const wrapper = (...params) => {
if(count < max){
count++;
return call(params);
}else{
return new PromiseConstructor((resolve, reject)=>{
queue.unshift({ params, resolve, reject });
});
}
}
return wrapper;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment