File size: 628 Bytes
d605f27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45

class SingleLock<T = void> {
	promise?: Promise<T>;
	resolve?: (result?: T) => void;


	constructor (locked: boolean = false) {
		if (locked)
			this.lock();
	}


	get locked (): boolean {
		return !!this.resolve;
	}


	lock (): Promise<T> {
		console.assert(!this.locked, "[SingleLock] duplicated locking, last locking has't been released yet.");

		this.promise = new Promise(resolve => this.resolve = resolve);

		return this.promise;
	}


	release (result?: T) {
		if (this.resolve) {
			this.resolve(result);
			this.resolve = null;
		}
	}


	wait (): Promise<T> {
		return this.promise;
	}
};



export {
	SingleLock,
};