Notes/src/public/app/utils/mutex.ts

30 lines
807 B
TypeScript
Raw Normal View History

export default class Mutex {
2024-07-25 00:12:24 +03:00
private current: Promise<void>;
constructor() {
this.current = Promise.resolve();
}
lock() {
2024-07-25 00:12:24 +03:00
let resolveFun: () => void;
const subPromise = new Promise<void>(resolve => resolveFun = () => resolve());
// Caller gets a promise that resolves when the current outstanding lock resolves
const newPromise = this.current.then(() => resolveFun);
// Don't allow the next request until the new promise is done
this.current = subPromise;
// Return the new promise
return newPromise;
};
2024-07-25 00:12:24 +03:00
async runExclusively(cb: () => Promise<void>) {
const unlock = await this.lock();
try {
return await cb();
}
finally {
unlock();
}
}
}