Skip to content

Instantly share code, notes, and snippets.

@amatiasq
Last active November 16, 2018 16:20
Show Gist options
  • Save amatiasq/969722bc64e4f165e73b to your computer and use it in GitHub Desktop.
Save amatiasq/969722bc64e4f165e73b to your computer and use it in GitHub Desktop.
This function will prevent a long operation to be executed twice in parallel. If the function is invoked a second time before the first time has completed it will receive the same promise from the first invocation without need to invoke the operation again.
function throttlePromise(operation) {
var promise = null;
return function() {
if (!promise) {
promise = operation.apply(this, arguments).finally(function() {
promise = null;
});
}
return promise;
};
}
var getUserData = throttlePromise(function() {
return AJAX.get('/user-data');
});
getUserData();
getUserData();
getUserData();
getUserData();
getUserData();
getUserData();
getUserData()
// only one ajax call will be executed until here
.then(function() {
// the previous invocation is complete so this will fire another ajax call
getUserData();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment