1
-
2
1
/**
3
2
* Promise-like object which can be passed around for resolving it later. It
4
3
* implements the "thenable" interface, so it can be used wherever a Promise
5
4
* could be used.
6
5
*
7
6
* In addition a "reject on timeout" functionality is provided.
8
7
*/
9
- export default class Deferred {
8
+ export default class Deferred < T = any > {
9
+ promise : Promise < T > ;
10
+ resolve : ( value : T | PromiseLike < T > ) => void ;
11
+ reject : ( reason ?: any ) => void ;
12
+ then : Promise < T > [ 'then' ] ;
13
+ catch : Promise < T > [ 'catch' ] ;
14
+ private _timeout ?: Timeout ;
15
+
10
16
/**
11
17
* Instantiates a Deferred object.
12
18
*/
13
19
constructor ( ) {
14
- this . promise = new Promise ( ( resolve , reject ) => {
15
- this . resolve = ( ... args ) => {
20
+ this . promise = new Promise < T > ( ( resolve , reject ) => {
21
+ this . resolve = ( value : T | PromiseLike < T > ) => {
16
22
this . clearRejectTimeout ( ) ;
17
- resolve ( ... args ) ;
23
+ resolve ( value ) ;
18
24
} ;
19
- this . reject = ( ... args ) => {
25
+ this . reject = ( reason ?: any ) => {
20
26
this . clearRejectTimeout ( ) ;
21
- reject ( ... args ) ;
27
+ reject ( reason ) ;
22
28
} ;
23
29
} ) ;
24
30
this . then = this . promise . then . bind ( this . promise ) ;
@@ -28,14 +34,14 @@ export default class Deferred {
28
34
/**
29
35
* Clears the reject timeout.
30
36
*/
31
- clearRejectTimeout ( ) {
37
+ clearRejectTimeout ( ) : void {
32
38
clearTimeout ( this . _timeout ) ;
33
39
}
34
40
35
41
/**
36
42
* Rejects the promise after the given timeout.
37
43
*/
38
- setRejectTimeout ( ms ) {
44
+ setRejectTimeout ( ms : number ) : void {
39
45
this . _timeout = setTimeout ( ( ) => {
40
46
this . reject ( new Error ( 'timeout' ) ) ;
41
47
} , ms ) ;
0 commit comments