npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@knnan/async-lock

v1.0.1

Published

A lightweight async mutex implementation with abort signal support

Readme

Async Lock

A lightweight, zero-dependency async mutex (mutual exclusion lock) implementation for JavaScript/Node.js with AbortSignal support.

Features

  • 🔒 Simple mutex implementation for async operations
  • ⏱️ Built-in timeout support
  • 🛑 AbortSignal integration for cancellable operations
  • 🪶 Zero dependencies
  • 📦 Tiny footprint
  • 🔧 Easy to use API
  • 🎯 TypeScript-friendly (with JSDoc annotations)

Installation

npm install @knnan/async-lock
yarn add @knnan/async-lock
pnpm add @knnan/async-lock

Usage

Basic Usage

import { AsyncMutex } from '@knnan/async-lock';

const mutex = new AsyncMutex();

// Acquire lock manually
const release = await mutex.acquire();
try {
    // Critical section - only one execution at a time
    await doSomethingCritical();
} finally {
    release(); // Always release the lock
}

Using runExclusive (Recommended)

The runExclusive method automatically handles lock acquisition and release:

const result = await mutex.runExclusive(async () => {
    // Critical section
    await updateSharedResource();
    return 'done';
});

With Timeout

Prevent deadlocks by setting a timeout:

// Acquire with timeout
try {
    const release = await mutex.acquireWithTimeout(5000); // 5 seconds
    try {
        await doSomething();
    } finally {
        release();
    }
} catch (error) {
    console.error('Failed to acquire lock within timeout');
}

// Or use runExclusiveWithTimeout
try {
    await mutex.runExclusiveWithTimeout(async () => {
        await doSomething();
    }, 5000);
} catch (error) {
    console.error('Operation timed out');
}

With AbortSignal

Cancel pending lock acquisitions:

const controller = new AbortController();

// Cancel after 3 seconds
setTimeout(() => controller.abort(), 3000);

try {
    const release = await mutex.acquire(controller.signal);
    try {
        await doSomething();
    } finally {
        release();
    }
} catch (error) {
    if (error.name === 'AbortError') {
        console.log('Lock acquisition was cancelled');
    }
}

API Reference

AsyncMutex

Constructor

const mutex = new AsyncMutex();

Creates a new mutex instance.

Methods

acquire(signal?: AbortSignal): Promise<Function>

Acquires the mutex lock. If the lock is already held, the promise will wait until it's released.

Parameters:

  • signal (optional): An AbortSignal to cancel the acquisition

Returns: A promise that resolves to a release function

Example:

const release = await mutex.acquire();
try {
    // critical section
} finally {
    release();
}
acquireWithTimeout(timeoutMs: number): Promise<Function>

Acquires the mutex with a timeout.

Parameters:

  • timeoutMs: Timeout in milliseconds

Returns: A promise that resolves to a release function, or rejects on timeout

Example:

const release = await mutex.acquireWithTimeout(5000);
runExclusive(fn: Function): Promise<any>

Executes a function exclusively, automatically managing the lock.

Parameters:

  • fn: An async function to execute

Returns: A promise that resolves to the return value of fn

Example:

const result = await mutex.runExclusive(async () => {
    return await doSomething();
});
runExclusiveWithTimeout(fn: Function, timeoutMs: number): Promise<any>

Executes a function exclusively with a timeout.

Parameters:

  • fn: An async function to execute
  • timeoutMs: Timeout in milliseconds

Returns: A promise that resolves to the return value of fn, or rejects on timeout

Example:

await mutex.runExclusiveWithTimeout(async () => {
    await doSomething();
}, 5000);

Use Cases

Preventing Race Conditions

const mutex = new AsyncMutex();
let counter = 0;

async function incrementCounter() {
    await mutex.runExclusive(async () => {
        const current = counter;
        await someAsyncOperation();
        counter = current + 1;
    });
}

// Safe concurrent calls
await Promise.all([
    incrementCounter(),
    incrementCounter(),
    incrementCounter()
]);

Database Connection Pool

const dbMutex = new AsyncMutex();

async function queryDatabase(sql) {
    return await dbMutex.runExclusive(async () => {
        const connection = await getConnection();
        try {
            return await connection.query(sql);
        } finally {
            await releaseConnection(connection);
        }
    });
}

File Access Synchronization

const fileMutex = new AsyncMutex();

async function writeToFile(data) {
    await fileMutex.runExclusive(async () => {
        await fs.promises.appendFile('data.txt', data);
    });
}

API Rate Limiting

const apiMutex = new AsyncMutex();

async function callAPI(endpoint) {
    return await apiMutex.runExclusive(async () => {
        const response = await fetch(endpoint);
        await delay(1000); // Rate limit: 1 request per second
        return response.json();
    });
}

Error Handling

Always use try-finally blocks when manually managing locks:

const release = await mutex.acquire();
try {
    await doSomething();
} catch (error) {
    // Handle errors
    console.error(error);
} finally {
    release(); // Always release, even on error
}

Or use runExclusive which handles this automatically:

try {
    await mutex.runExclusive(async () => {
        await doSomething();
    });
} catch (error) {
    console.error(error);
}

Common Pitfalls

❌ Forgetting to Release

// BAD: Lock is never released
const release = await mutex.acquire();
await doSomething(); // If this throws, release() never runs
release();

✅ Always Use Finally

// GOOD: Lock is always released
const release = await mutex.acquire();
try {
    await doSomething();
} finally {
    release();
}

❌ Nested Locks (Deadlock)

// BAD: Will deadlock
await mutex.runExclusive(async () => {
    await mutex.runExclusive(async () => {
        // This will never execute
    });
});

✅ Use Separate Mutexes or Avoid Nesting

// GOOD: Sequential execution
await mutex.runExclusive(async () => {
    await doSomething();
});
await mutex.runExclusive(async () => {
    await doSomethingElse();
});

Browser Support

Works in all modern browsers and Node.js environments that support:

  • Promises
  • Async/await
  • AbortSignal (for cancellation features)

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

MIT License - see LICENSE file for details

Author

Your Name

Links

Changelog

1.0.0

  • Initial release
  • Basic mutex functionality
  • AbortSignal support
  • Timeout support
  • runExclusive helpers