1
- type DeferredPromiseOptions = {
1
+ type DeferredPromiseOptions < T > = {
2
2
timeout ?: number ;
3
+ onTimeout ?: ( resolve : ( value : T ) => void , reject : ( reason : Error ) => void ) => void ;
3
4
} ;
4
5
5
6
/** Creates a promise and exposes its resolve and reject methods, with an optional timeout. */
7
+ // eslint-disable-next-line @typescript-eslint/no-empty-object-type
6
8
export class DeferredPromise < T > extends Promise < T > {
7
9
resolve ! : ( value : T ) => void ;
8
10
reject ! : ( reason : unknown ) => void ;
9
11
private timeoutId ?: NodeJS . Timeout ;
10
12
11
- constructor ( resolver : ( resolve : ( value : T ) => void , reject : ( reason : Error ) => void ) => void , timeout ?: number ) {
13
+ constructor (
14
+ executor : ( resolve : ( value : T ) => void , reject : ( reason : Error ) => void ) => void ,
15
+ { timeout, onTimeout } : DeferredPromiseOptions < T > = { }
16
+ ) {
12
17
let resolveFn : ( value : T ) => void ;
13
18
let rejectFn : ( reason ?: unknown ) => void ;
14
19
@@ -24,12 +29,12 @@ export class DeferredPromise<T> extends Promise<T> {
24
29
25
30
if ( timeout !== undefined ) {
26
31
this . timeoutId = setTimeout ( ( ) => {
27
- this . reject ( new Error ( "Promise timed out" ) ) ;
32
+ onTimeout ?. ( this . resolve , this . reject ) ;
28
33
} , timeout ) ;
29
34
}
30
35
31
- if ( resolver ) {
32
- resolver (
36
+ if ( executor ) {
37
+ executor (
33
38
( value : T ) => {
34
39
if ( this . timeoutId ) clearTimeout ( this . timeoutId ) ;
35
40
this . resolve ( value ) ;
@@ -42,7 +47,7 @@ export class DeferredPromise<T> extends Promise<T> {
42
47
}
43
48
}
44
49
45
- static fromPromise < T > ( promise : Promise < T > , options : DeferredPromiseOptions = { } ) : DeferredPromise < T > {
50
+ static fromPromise < T > ( promise : Promise < T > , options : DeferredPromiseOptions < T > = { } ) : DeferredPromise < T > {
46
51
return new DeferredPromise < T > ( ( resolve , reject ) => {
47
52
promise
48
53
. then ( ( value ) => {
@@ -51,6 +56,6 @@ export class DeferredPromise<T> extends Promise<T> {
51
56
. catch ( ( reason ) => {
52
57
reject ( reason as Error ) ;
53
58
} ) ;
54
- } , options . timeout ) ;
59
+ } , options ) ;
55
60
}
56
61
}
0 commit comments