0 day streak
javascript / expert
Snippet

Asynchronous Mutex for Exclusive Resource Access

A Mutex ensures that only one asynchronous operation can access a critical section at a time. It chains promises to create a queue where each operation waits for the previous one to resolve, preventing race conditions in shared environments like server-side caches.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Mutex {
#promise = Promise.resolve();
async acquire() {
let release;
const next = new Promise(res => release = res);
const current = this.#promise;
this.#promise = current.then(() => next);
await current;
return release;
}
}
// Usage in Next.js Route Handler
const mutex = new Mutex();
export async function POST() {
const release = await mutex.acquire();
try {
// Critical section
} finally {
release();
}
}
nextjs
Breakdown
1
this.#promise = current.then(() => next);
Appends the new lock request to the existing chain of promises.
2
await current;
Waits for all previously queued operations to finish before proceeding.
3
return release;
Returns a function that resolves the 'next' promise, allowing the next queued task to run.