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

typescript
import { registerLocaleData } from '@angular/common';
import localeFr from '@angular/common/locales/fr';
import localeFrExtra from '@angular/common/locales/extra/fr';
import localeDe from '@angular/common/locales/de';

Locale-aware bootstrapping in Angular

i18n localization dependency-injection
Intermediate 8 steps
typescript
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import * as Joi from 'joi';
 

Validating env config at boot in NestJS

configuration schema-validation environment-variables
Intermediate 8 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Cache } from 'cache-manager';
import { InjectRepository } from '@nestjs/typeorm';

A cache-aside country lookup in NestJS

cache-aside dependency-injection batch-lookup
Intermediate 8 steps
typescript
import { Injectable, effect, signal, computed } from '@angular/core';
 
interface Preferences {
  theme: 'light' | 'dark';

A signal-based preferences store in Angular

signals state-management persistence
Intermediate 7 steps
go
func (w *Watcher) resetDebounce(d time.Duration) {
	if !w.timer.Stop() {
		select {
		case <-w.timer.C:

Debouncing a stream of events in Go

debounce timers channels
Advanced 7 steps
typescript
import { useEffect, useState } from "react";
 
interface Section {
  id: string;

Building a scroll-spy hook in React

custom-hooks intersectionobserver dom-observation
Intermediate 8 steps

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