I want to lock an async function from simultaneous execution. The function can be only executed by one caller and it should get true as output after execution where others get false as the return without executing the logical content of the function. Others should not wait for the current caller to complete.
This is what I tried so far:
class Lock {
constructor() {
this.locked = false;
}
lock(resolve) {
if (this.locked) {
resolve(false)
}
this.locked = true
return
}
release(resolve) {
this.locked = false;
resolve(true)
}
}
let lock = new Lock();
function myFunction() {
return new Promise(resolve => {
lock.lock(resolve);
//do something - this takes time includes some api calls and db operations
lock.release(resolve);
})
}
async function callSite() {
const executed = await myFunction();
if(executed){
//do something
}
else{
//do another thing
}
}
But seems like it doesn't work as expected. Can anyone help me to improve this?