Skip to content

Instantly share code, notes, and snippets.

@chrisui
Created September 1, 2015 18:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisui/a1481eeaa4179121fa7d to your computer and use it in GitHub Desktop.
Save chrisui/a1481eeaa4179121fa7d to your computer and use it in GitHub Desktop.
Promise Gating
/**
* 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