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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A queue of pending resolve callbacks turns a boolean flag into a fair, FIFO async lock.
- 2Releasing inside a finally block guarantees the lock is freed even if the task throws.
- 3Even single-threaded JavaScript needs mutual exclusion because await yields control mid-operation.
Related explainers
java
public class SlidingLogRateLimiter { private final int maxRequests; private final long windowMillis;
How a sliding-log rate limiter works
rate-limiting
concurrency
sliding-window
Advanced
8 steps
typescript
import { Injectable, UnauthorizedException } from '@nestjs/common'; import { PassportStrategy } from '@nestjs/passport'; import { ExtractJwt, Strategy } from 'passport-jwt'; import { ConfigService } from '@nestjs/config';
How a JWT strategy authenticates in NestJS
authentication
jwt
passport
Intermediate
7 steps
go
package theme import ( "fmt"
Per-tenant HTML templates with Gin's renderer
multi-tenancy
concurrency
html-templates
Advanced
8 steps
python
import time import threading from enum import Enum from functools import wraps
Building a circuit breaker in Python
circuit-breaker
resilience
decorators
Advanced
7 steps
typescript
import { Injectable } from '@angular/core'; import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from '@angular/common/http'; import { BehaviorSubject, Observable, throwError } from 'rxjs'; import { catchError, filter, take, switchMap } from 'rxjs/operators';
Refreshing auth tokens in an Angular interceptor
http-interceptor
token-refresh
rxjs
Advanced
8 steps
php
<?php namespace App\Http\Middleware;
Idempotent requests with Laravel middleware
idempotency
middleware
caching
Advanced
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-an-async-mutex-in-typescript-explained-typescript-5cee/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.