async-mutex icon indicating copy to clipboard operation
async-mutex copied to clipboard

All examples use fluent pattern

Open PonchoPowers opened this issue 1 year ago • 1 comments

All the examples use a fluent pattern, but wouldn't it be good to have an example such as a real word example that is clear to follow and doesn't use a fluent pattern like so:

import { Mutex } from 'async-mutex';

class ConcurrentDictionary<K, V> {
    private dictionary: Map<K, V>;
    private mutex: Mutex;

    constructor() {
        this.dictionary = new Map<K, V>();
        this.mutex = new Mutex();
    }

    async set(key: K, value: V): Promise<void> {
        const release = await this.mutex.acquire();
        try {
            this.dictionary.set(key, value);
        } finally {
            release();
        }
    }

    async get(key: K): Promise<V | undefined> {
        const release = await this.mutex.acquire();
        try {
            return this.dictionary.get(key);
        } finally {
            release();
        }
    }

    async delete(key: K): Promise<boolean> {
        const release = await this.mutex.acquire();
        try {
            return this.dictionary.delete(key);
        } finally {
            release();
        }
    }

    async has(key: K): Promise<boolean> {
        const release = await this.mutex.acquire();
        try {
            return this.dictionary.has(key);
        } finally {
            release();
        }
    }

    async clear(): Promise<void> {
        const release = await this.mutex.acquire();
        try {
            this.dictionary.clear();
        } finally {
            release();
        }
    }
}

PonchoPowers avatar Oct 13 '24 15:10 PonchoPowers

I would also appreciate documentation for the "legacy" way of using this library.

mukunku avatar Dec 18 '24 16:12 mukunku