mirror of
https://github.com/aljazceru/turso.git
synced 2025-12-21 02:14:18 +01:00
wip
This commit is contained in:
29
bindings/javascript/packages/common/async-lock.ts
Normal file
29
bindings/javascript/packages/common/async-lock.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
export class AsyncLock {
|
||||
locked: boolean;
|
||||
queue: any[];
|
||||
constructor() {
|
||||
this.locked = false;
|
||||
this.queue = []
|
||||
}
|
||||
async acquire() {
|
||||
if (!this.locked) {
|
||||
this.locked = true;
|
||||
return Promise.resolve();
|
||||
} else {
|
||||
const block = new Promise(resolve => { this.queue.push(resolve) });
|
||||
return block;
|
||||
}
|
||||
}
|
||||
release() {
|
||||
if (this.locked == false) {
|
||||
throw new Error("invalid state: lock was already unlocked");
|
||||
}
|
||||
const item = this.queue.shift();
|
||||
if (item != null) {
|
||||
this.locked = true;
|
||||
item();
|
||||
} else {
|
||||
this.locked = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user