Created
November 4, 2021 21:22
-
-
Save dested/ef3a1e6313b4924269175ce5d07c92b6 to your computer and use it in GitHub Desktop.
Await Locker
This file contains hidden or 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
export class AwaitLocker { | |
private static lockerCallbacks: {[key: string]: {callback?: () => void}[]} = {}; | |
static async startLock(key: string) { | |
if (!AwaitLocker.lockerCallbacks[key]) { | |
AwaitLocker.lockerCallbacks[key] = []; | |
} | |
if (AwaitLocker.lockerCallbacks[key].length > 0) { | |
let callback: () => void; | |
const promise = new Promise<void>((res) => { | |
callback = res; | |
}); | |
AwaitLocker.lockerCallbacks[key].push({callback: callback!}); | |
await promise; | |
} else { | |
AwaitLocker.lockerCallbacks[key].push({callback: undefined}); | |
} | |
} | |
static async releaseLock(key: string) { | |
// NEVER AWAIT THIS | |
if (!AwaitLocker.lockerCallbacks[key]) { | |
AwaitLocker.lockerCallbacks[key] = []; | |
} | |
AwaitLocker.lockerCallbacks[key] = AwaitLocker.lockerCallbacks[key].slice(1); | |
if (AwaitLocker.lockerCallbacks[key].length > 0) { | |
AwaitLocker.lockerCallbacks[key][0].callback?.(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment