forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlock.ts
More file actions
40 lines (36 loc) · 1.31 KB
/
Copy pathlock.ts
File metadata and controls
40 lines (36 loc) · 1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
export class AsyncLock {
private permits: number = 1;
private promiseResolverQueue: Array<(v: boolean) => void> = [];
async inLock<T>(func: () => Promise<T> | T): Promise<T> {
try {
await this.lock();
return await func();
} finally {
this.unlock();
}
}
private async lock() {
if (this.permits > 0) {
this.permits = this.permits - 1;
return;
}
await new Promise<boolean>(resolve => this.promiseResolverQueue.push(resolve));
}
private unlock() {
this.permits += 1;
if (this.permits > 1 && this.promiseResolverQueue.length > 0) {
throw new Error('this.permits should never be > 0 when there is someone waiting.');
} else if (this.permits === 1 && this.promiseResolverQueue.length > 0) {
// If there is someone else waiting, immediately consume the permit that was released
// at the beginning of this function and let the waiting function resume.
this.permits -= 1;
const nextResolver = this.promiseResolverQueue.shift();
// Resolve on the next tick
if (nextResolver) {
setTimeout(() => {
nextResolver(true);
}, 0);
}
}
}
}