Skip to content

Instantly share code, notes, and snippets.

@t-ski
Last active May 24, 2024 14:42
Show Gist options
  • Save t-ski/eca16abcd630e1205530fe388e67204e to your computer and use it in GitHub Desktop.
Save t-ski/eca16abcd630e1205530fe388e67204e to your computer and use it in GitHub Desktop.
Asynchronous mutex class for lock on callback functions.
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