Skip to content

Instantly share code, notes, and snippets.

@justinobney
Last active August 29, 2015 14:13
Show Gist options
  • Save justinobney/108dc01fccf0bcd5b857 to your computer and use it in GitHub Desktop.
Save justinobney/108dc01fccf0bcd5b857 to your computer and use it in GitHub Desktop.
Create an observable that accepts a list of callbacks(returning promises) to execute keeping only an optional number in flight at one time
function throttledPromiseObserver(callbacks, maxPending, checkInterval) {
var remainingCalls = callbacks.length;
var pendingCalls = 0;
var callIdx = 0;
var _checkInterval = checkInterval || 100;
var _maxPending = maxPending || 0;
return Rx.Observable.create(bufferedPromiseCalls);
function bufferedPromiseCalls(observer) {
check();
function check() {
if (remainingCalls) {
if (_maxPending === 0 || pendingCalls < _maxPending) {
pendingCalls++;
remainingCalls--;
try {
callbacks[callIdx++]().then(onDone, onDone); //observer.onError
}
catch(e){
observer.onError(e);
}
}
setTimeout(check, _checkInterval);
}
}
function onDone(result) {
pendingCalls--;
observer.onNext(result)
if (remainingCalls === 0 && pendingCalls === 0) {
observer.onCompleted();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment