oh-my-git/web/web-shell/mutex.js
2023-09-07 17:46:58 +02:00

25 lines
525 B
JavaScript

export class Mutex {
private mutex = Promise.resolve()
lock(): PromiseLike<() => void> {
let begin: (unlock: () => void) => void = (unlock) => {}
this.mutex = this.mutex.then(() => {
return new Promise(begin)
})
return new Promise((res) => {
begin = res
})
}
async dispatch(fn) {
const unlock = await this.lock()
try {
return await Promise.resolve(fn())
} finally {
unlock()
}
}
}