Implementing your own Mutex in JavaScript
As soon as you start building a complex application, you have to deal with concurrency. Well, in Javascript concurrency is not something that you turn on explicitly - It is always present. That leads to a ton of concurrency patterns out in the market to pick from.
One old school pattern is called the Mutex.
The following code shows an implementation of the Mutex, if you decide to not rely on 3rd party libraries that provide such an implementation.
type AnyF = (...x: any[]) => any
class Mutex {
? ? private mutex: Promise<any>
? ? private toExecuteF
? ? constructor(toExecuteF: AnyF) {
? ? ? ? this.mutex ?= Promise.resolve()
? ? ? ? this.toExecuteF = toExecuteF
? ? }
? ? exec(...a: any[]) {
? ? ? ? this.mutex = this.mutex.then(async () => {
? ? ? ? ? ? await this.toExecuteF(...a)
? ? ? ? }).catch(e => {
? ? ? ? ? ? throw e
? ? ? ? })
? ? ? ? return this.mutex
? ? }
}
/**
?* testing our Mutex
?*/
// testing helper:
// it runs the function arg just before printing the consol.log
function test(f?: AnyF) {
? ? let mutex = new Mutex(async (n: number) => {
? ? ? ? // placing a sleep here for testing our mutex
? ? ? ? await new Promise(r => setTimeout(r, Math.random() * 1000))
? ? ? ? if(f) f()
? ? ? ? console.log(n)
? ? })
? ? mutex.exec(1)
? ? mutex.exec(2)
? ? mutex.exec(3)
? ? mutex.exec(4)
}
test()
// test(() => {throw new Error("eee")})