typescript 48 lines · 7 steps

Building an async mutex in TypeScript

A promise-based lock that serializes async work so overlapping operations can't corrupt shared state.

Explained by highlit
1type Task<T> = () => Promise<T>;
2 
3export class Mutex {
4 private queue: Array<() => void> = [];
5 private locked = false;
6 
7 private acquire(): Promise<void> {
8 if (!this.locked) {
9 this.locked = true;
10 return Promise.resolve();
11 }
12 return new Promise((resolve) => {
13 this.queue.push(resolve);
14 });
15 }
16 
17 private release(): void {
18 const next = this.queue.shift();
19 if (next) {
20 next();
21 } else {
22 this.locked = false;
23 }
24 }
25 
26 async runExclusive<T>(task: Task<T>): Promise<T> {
27 await this.acquire();
28 try {
29 return await task();
30 } finally {
31 this.release();
32 }
33 }
34}
35 
36export class Counter {
37 private value = 0;
38 private readonly mutex = new Mutex();
39 
40 async increment(): Promise<number> {
41 return this.mutex.runExclusive(async () => {
42 const current = this.value;
43 await Promise.resolve();
44 this.value = current + 1;
45 return this.value;
46 });
47 }
48}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A queue of pending resolve callbacks turns a boolean flag into a fair, FIFO async lock.
  2. 2Releasing inside a finally block guarantees the lock is freed even if the task throws.
  3. 3Even single-threaded JavaScript needs mutual exclusion because await yields control mid-operation.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building an async mutex in TypeScript — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code