Last active
May 24, 2024 14:42
-
-
Save t-ski/eca16abcd630e1205530fe388e67204e to your computer and use it in GitHub Desktop.
Asynchronous mutex class for lock on callback functions.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class AsyncMutex { | |
constructor() { | |
this.acquireQueue = []; | |
this.isLocked = false; | |
} | |
lock(callback) { | |
return new Promise(resolveOuter => { | |
new Promise(resolveInner => { | |
if(this.isLocked) { | |
this.acquireQueue.push(resolveInner); | |
return; | |
} | |
this.isLocked = true; | |
resolveInner(); | |
}) | |
.then(() => { | |
const callbackResults = callback(); | |
((callbackResults instanceof Promise) | |
? callbackResults | |
: Promise.resolve(callbackResults)) | |
.then(results => { | |
this.isLocked = !!this.acquireQueue.length; | |
(this.acquireQueue.shift() || (() => {}))(); | |
resolveOuter(results); | |
}); | |
}); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment