Last active
November 16, 2018 16:20
-
-
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.
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 throttlePromise(operation) { | |
var promise = null; | |
return function() { | |
if (!promise) { | |
promise = operation.apply(this, arguments).finally(function() { | |
promise = null; | |
}); | |
} | |
return promise; | |
}; | |
} |
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
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