1 |
|
2 |
|
3 | export class Mutex {
|
4 | private mutex = Promise.resolve();
|
5 |
|
6 | public lock(): PromiseLike<() => void> {
|
7 | let begin: (unlock: () => void) => void = () => { };
|
8 |
|
9 | this.mutex = this.mutex.then(() => {
|
10 | return new Promise(begin);
|
11 | });
|
12 |
|
13 | return new Promise((res) => {
|
14 | begin = res;
|
15 | });
|
16 | }
|
17 |
|
18 | public async dispatch<T>(fn: (() => T) | (() => PromiseLike<T>)): Promise<T> {
|
19 | const unlock = await this.lock();
|
20 | try {
|
21 | return await Promise.resolve(fn());
|
22 | } finally {
|
23 | unlock();
|
24 | }
|
25 | }
|
26 | }
|
27 |
|
\ | No newline at end of file |