Skip to content

mutex

The mutex decorator ensures that one or more class methods are executed asynchronously with a concurrency limit of 1.

Importing

import { mutex } from "@tai-kun/surrealdb/utils";

Usage

function mutex(
target: (...args: any) => PromiseLike<any>,
context: ClassMethodDecoratorContext,
): (this: any, ...args: any) => Promise<any>;

Arguments

target

The class method to be decorated.

context

The Stage 3 class method decorator context.

Return Value

An asynchronous function with its concurrency limited to 1.

Example

The following example demonstrates the difference in execution timing of asynchronous operations with and without the mutex decorator:

import { mutex } from "@tai-kun/surrealdb/utils";
class Runner {
async runWithoutMutex(ms: number, value: string) {
await sleep(ms);
console.log(value);
}
@mutex
async runWithMutex(ms: number, value: string) {
await sleep(ms);
console.log(value);
}
}
const runner = new Runner();
// without mutex
await Promise.all([
runner.runWithoutMutex(1000, "A"),
runner.runWithoutMutex(500, "B"),
runner.runWithoutMutex(0, "C"),
]);
// with mutex
await Promise.all([
runner.runWithMutex(1000, "A"),
runner.runWithMutex(500, "B"),
runner.runWithMutex(0, "C"),
]);

Output:

C
B
A
A
B
C