In the previous example we saw how to manage simple counter state using atomic operations. For more complex state we can use a mutex to safely access data across multiple asynchronous operations.
Running the program shows that the counters updated as expected.
In this TypeScript version, we use the async-mutex package to implement mutex functionality. The Container class uses a Mutex to ensure thread-safe access to the counters map. The inc method is now asynchronous, using await to acquire and release the mutex.
The main function is also asynchronous, allowing us to use await with Promise.all to wait for all increments to complete. We use async functions instead of goroutines, and Promises instead of channels for concurrency.
Note that TypeScript runs on a single-threaded event loop by default, so true parallelism isn’t achieved here. However, this example demonstrates how to handle concurrent access to shared state in an asynchronous TypeScript application.
Next we’ll look at implementing this same state management task using only asynchronous functions and message passing.