mirror of
https://github.com/git-learning-game/oh-my-git.git
synced 2024-09-26 18:07:47 +02:00
25 lines
525 B
JavaScript
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()
|
||
|
}
|
||
|
}
|
||
|
}
|