JavaScript Semaphore
A promise-based semaphore implementation suitable to be used with ES7 async/await.
But JavaScript is single-threaded and doesn't need semaphores!
This package can be used to synchronize functions that span multiple iterations of the event loop and prevent other code from being executed while your function is waiting for some event.
Install
yarn add semaphore-async-await
Usage
import Semaphore from 'semaphore-async-await';
(async () => {
const lock = new Semaphore(1);
const wait = (ms) => new Promise(r => setTimeout(r, ms));
let globalVar = 0;
(async () => {
await lock.wait();
const localCopy = globalVar;
await wait(500);
globalVar = localCopy + 1;
lock.signal();
})();
console.log(lock.tryAcquire() === false);
(async () => {
const didAcquireLock = await lock.waitFor(5000);
if (didAcquireLock) {
const localCopy = globalVar;
await wait(500);
globalVar = localCopy + 1;
lock.signal();
}
})();
lock.execute(async () => {
const localCopy = globalVar;
await wait(500);
globalVar = localCopy + 1;
});
await wait(2000);
console.log(globalVar === 3);
})();
Methods
- Semaphore(permits) ⇒
Semaphore
Creates a semaphore with the given number of permits, i.e. things being allowed to run in parallel. To create a lock that only lets one thing run at a time, give it one permit. This number can also be negative.
- wait() ⇒
Promise
Returns a promise used to wait for a permit to become available.
- waitFor(milliseconds) ⇒
Promise
Same as wait except the promise returned gets resolved with false if no permit becomes available in time.
- tryAcquire() ⇒
boolean
Synchronous function that tries to acquire a permit and returns true if successful, false otherwise.
- signal()
Increases the number of permits by one. If there are other functions waiting, one of them will
continue to execute in a future iteration of the event loop.
- execute(func) ⇒
Promise
Schedules func to be called once a permit becomes available. Returns a promise that resolves to the return value of the function.
License
MIT