Synchronize Your JavaScript Code With Async-Mutex
Share resources or control number of instances with async-mutex

JavaScript runtime is single-threaded, but the asynchronous nature of promises introduces the necessity to synchronize access on resources in certain use cases.
Event handlers are asynchronous events that can benefit from mutual exclusion. Events like scroll and button click handlers can fire off multiple events within a second, but sometimes you only need the first event (and the others are undesirable). We need a way to be able to guarantee the order of the asynchronous events.
About async-mutex
async-mutex is an npm package that implements the synchronizing primitives, allowing you to control asynchronous events deterministically.
The synchronizing primitives are Mutex and Semaphore.
- Mutex (short for mutual exclusion) is a lock. Once someone acquires the lock, any other attempts to acquire it will block until the holder of the lock releases it!
- Sempahore is similar to a Mutex except it can allow multiple people to ‘acquire’ it. This is useful for cases when you can only allow up to X asynchronous events at a time.
async-mutex also exposes a withTimeout decorator. In summary, when you wrap a Mutex or Semaphore with a withTimeout decoration, you can specify a maximum time of blocking on a lock before the requester is rejected.
You can install async-mutex through the following command
npm install --save async-mutexOnce installed, you can import the objects exposed by async-mutex
import { Mutex, Semaphore, withTimeout } from 'async-mutex';Ready? let’s start exploring the usage of these synchronizing primitives. I will introduce our example first. Afterwards, I will show examples of proper mutual exclusion with Mutex and Semaphore.
Ordered Server Counter

The example above is an ordered server counter that we wish to build. When you click on the button:
- An asynchronous request is sent to a server
- The server increments an internal counter
- The server returns the current counter value
- The client (our webpage) displays the counter in a Toast shown above.
It is important the the order of the numbers is preserved when received. So how can we synchronize the order of the requests? We know that network requests are asynchronous. It is totally possible for the first request to take longer to arrive than the second request, or the second request to take longer than the third request, and so on. This out-of-order arrival of requests will be a problem for our application.
The ‘No synchronization’ approach
What would happen if we were to develop this application with no synchronization constructs? Here is a sample implementation of a simulation of this application with no synchronization.








