@openally/mutex
v4.0.0
Published
Another Mutex/Semaphore implementation with first-class support of AbortSignal
Readme
Requirements
- Node.js v24 or higher
Getting Started
This package is available in the Node Package Repository and can be easily installed with npm or yarn.
$ npm i @openally/mutex
# or
$ yarn add @openally/mutexUsage example
Use Mutex to limit concurrent work:
import { Mutex } from "@openally/mutex";
const mutex = new Mutex({ concurrency: 2 });
async function save(record: Record<string, unknown>) {
using release = await mutex.acquire({
signal: AbortSignal.timeout(5_000),
delayBeforeAutomaticRelease: 30_000
});
await writeRecord(record);
}
await Promise.all(records.map(save));Use TaskGroup when tasks are scheduled without awaiting each one immediately:
import { Mutex, TaskGroup } from "@openally/mutex";
const tasks = new TaskGroup({
mutex: new Mutex({ concurrency: 10 })
});
for (const user of users) {
tasks.add(`email:${user.id}`, () => sendEmail(user));
}
const failures = await tasks.drain();
for (const { name, error } of failures) {
console.error(`${name} failed`, error);
}API
Mutexlimits concurrent asynchronous work and supportsAbortSignalcancellation while waiting.TaskGroupschedules tasks under a concurrency limit and collects their failures.MutexCanceledErroridentifies cancellation bycancel(),reset(), orAbortSignal.
License
MIT
