Created
September 1, 2015 18:03
-
-
Save chrisui/a1481eeaa4179121fa7d to your computer and use it in GitHub Desktop.
Promise Gating
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
/** | |
* Create a "gated" (throttled) version of the user function. This throttling is not time | |
* based but rather throttles execution to prevent two async actions occuring in parallel. | |
* Ie. Two syncronous calls to the returned function will return reference to the same promise | |
* - An example use case of this would be to prevent firing too many api requests to the same | |
* endpoint in a short amount of time | |
* @param {Function} func func *must* return a promise | |
* @returns {Function} throttled function which will always return a promise | |
*/ | |
export function gate(func) { | |
let lastPromise = null; | |
return function callUserFunc(...args) { | |
if (!lastPromise) { | |
// Track promise result from func call and | |
// hold onto it until the promise is resolved | |
lastPromise = func(...args).then( | |
function reset() { | |
lastPromise = null; | |
}, | |
function resetAndThrow(err) { | |
lastPromise = null; | |
throw err; | |
} | |
); | |
} | |
return lastPromise; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment