flexlock-cb
flexlock-cb
is a very small, memory-concious, flexible locking library without
dependencies but with typescript
definitions (see in the bottom). Optimized even further than
flexlock
for the use with callbacks instead of promises.
npm i flexlock-cb --save
It is similar to other in-memory locking library like mutexify
,
mutex-js
, await-lock
, and many more,
but with more flexibility in how to use it.
This makes it sturdier and more practical in many cases.
simple basic API
const createLockCb = const lock =
Propagation of errors and results to a callback
{ // err === null // data === 'important'}
Promises are returned if no callback is added
const promise = // Without passing in a callback, promises will be created promise // This way you can support both callback and promise based APIs
Timeouts in case anther lock never returns
{ /* Due to a bug it never unlocks */ } {}
release handlers both once and for every release
{} {} const lock = // Called everytime the lock is releasedlock // Called next time the lock is released await lock // Promise API available as well
Like for Promises, two separate callbacks can be specified
{} {}
sync handlers, for when you want to make sure that other locks are done
const lock = const result = await lock result === 123 // the result is passed to the callback
In case you need it, a reference to the lock is also passed in:
const result = await lock
Its also possible to wrap a method into a sync lock:
const fn = lock
Be aware that any errors that might occur will by-default result in uncaught exceptions!
You can handle those errors by passing an error handler when creating the lock:
const lock = const fn = lock
... or by adding a error handler directly when wrapping:
const fn2 = lock
Destroying locks
When closing down an application you may want to also close all operations and prevent future operations:
const lock = locktry catch err // err ... will be the error passed-in to .destroy()
Typescript recommendation
Figuring out the proper typing was quite tricky for flexlock-cb.
To make things easier for users, it exports a Callbacks
type that
can be used to reduce
//// Overloading for the two use cases (return type void or Promise)// If you would like to improve this, vote for// https://github.com/Microsoft/TypeScript/issues/29182// // Separate definitions with the support for timeouts