File

src/utils/mutex.ts

Index

Properties
Methods

Properties

Private mutex
Type : Promise<void>
Default value : Promise.resolve()

Methods

Public lock
lock(callback: () => void)
Type parameters :
  • T
Parameters :
Name Type Optional
callback function No
Returns : Promise<T>
export class Mutex {
  private mutex: Promise<void> = Promise.resolve();

  public lock<T>(callback: () => T | Promise<T>): Promise<T> {
    // Locking mechanism: Wait for the current mutex chain to resolve,
    // then run the callback and capture its result
    const resultPromise = this.mutex.then(() => callback());

    // Update the mutex to wait for the current operation to finish
    this.mutex = resultPromise.then(() => undefined, () => undefined);

    // Return the result of the callback, so the caller gets its value
    return resultPromise;
  }
}
export default Mutex;

results matching ""

    No results matching ""