23 lines
542 B
TypeScript
Raw Normal View History

export class LockManager {
private locks: { [key: string]: Promise<any> };
2024-04-26 02:10:37 -04:00
constructor() {
this.locks = {};
}
2024-04-26 02:10:37 -04:00
async acquireLock<T>(key: string, task: () => Promise<T>): Promise<T> {
if (!this.locks[key]) {
this.locks[key] = new Promise<T>(async (resolve, reject) => {
try {
const result = await task();
resolve(result);
} catch (error) {
reject(error);
} finally {
delete this.locks[key];
2024-04-26 02:10:37 -04:00
}
});
2024-04-26 02:10:37 -04:00
}
return await this.locks[key];
}
}