JavaScript Semaphore
A promise-based semaphore implementation suitable to be used with async/await.
Spare me the details, all I need is a lock.
Just import { Lock } from 'semaphore-async-await'
, acquire the lock by calling await lock.acquire()
and release it when you're done by calling lock.release()
.
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.
Suppose you have a function
{ const data = await ; const modifiedData = await ; return ;}
Calling this function repeatedly could lead to overlapping read/writes. To avoid this problem, a lock can be added like so:
const lock = 1; { await lock; await ; lock;}
Asynchronous functions like criticalFunction
are executed in multiple chunks of code on the event loop, this package makes it possible to enforce an ordering in these chunks.
Install
yarn add semaphore-async-await
API
Usage
; async { // A Semaphore with one permit is a lock const lock = 1; // Helper function used to wait for the given number of milliseconds const wait = ; let globalVar = 0; async { // This waits (without blocking the event loop) until a permit becomes available await lock; const localCopy = globalVar; await ; globalVar = localCopy + 1; // Signal releases the lock and lets other things run lock; }; // This returns false because the function above has acquired the lock // and is scheduled to continue executing once the main function yields or // returns console; // Similar to the function above but using waitFor instead of wait. We // give it five seconds to wait which is enough time for it to acquire // the lock async { // This waits for at least five seconds, trying to acquire a permit. const didAcquireLock = await lock; if didAcquireLock const localCopy = globalVar; await ; globalVar = localCopy + 1; // Signal releases the lock and lets other things run lock; }; // Alternative to using wait()/signal() directly lock; // Wait for everything to finish await ; console;};
License
MIT