-
Notifications
You must be signed in to change notification settings - Fork 9
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
203a123
commit bfd9f2e
Showing
13 changed files
with
174 additions
and
127 deletions.
There are no files selected for viewing
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
export class AsyncLock { | ||
private queue: PromiseWithResolvers<void>[]; | ||
|
||
constructor() { | ||
this.queue = []; | ||
} | ||
|
||
async run<T>(fn: () => Promise<T>): Promise<T> { | ||
await this.lock(); | ||
const result = await fn(); | ||
this.release(); | ||
return result; | ||
} | ||
|
||
async close() { | ||
for (const lock of this.queue) { | ||
lock.resolve(); | ||
await lock.promise; | ||
} | ||
} | ||
|
||
private async lock() { | ||
const prev = this.queue.at(-1); | ||
const next = Promise.withResolvers<void>(); | ||
this.queue.push(next); | ||
await prev?.promise; | ||
} | ||
|
||
private release() { | ||
const lock = this.queue.shift(); | ||
lock?.resolve(); | ||
} | ||
} |
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
Oops, something went wrong.