Last active
August 29, 2015 14:13
-
-
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
This file contains 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
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