Last active
December 14, 2017 21:27
-
-
Save trevorhreed/a86bd8e279c140b3153200df130dde7b to your computer and use it in GitHub Desktop.
Throttles the number of concurrent calls to a promise function
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
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