Created
April 28, 2023 21:10
-
-
Save epreston/6dd95501df9fba679809ec2802c3bbbd to your computer and use it in GitHub Desktop.
promise based semaphore - caller controllable promise interface
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 Semaphore() { | |
// controllable promise | |
let _resolve; | |
let _reject; | |
const promiseSemaphore = new Promise((resolve, reject) => { | |
_resolve = resolve; | |
_reject = reject; | |
}); | |
promiseSemaphore.resolve = _resolve; | |
promiseSemaphore.reject = _reject; | |
return promiseSemaphore; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is used to simplify resource management or resource initialisation.
First caller will await completion. Other callers will get the promise interface to either wait as well or continue immediately.
Example for something that may need to be awaited but can run again.
For something that should only be run once, don't reset the promise variable.