1- type DeferredPromiseOptions = {
1+ type DeferredPromiseOptions < T > = {
22 timeout ?: number ;
3+ onTimeout ?: ( resolve : ( value : T ) => void , reject : ( reason : Error ) => void ) => void ;
34} ;
45
56/** 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
68export class DeferredPromise < T > extends Promise < T > {
79 resolve ! : ( value : T ) => void ;
810 reject ! : ( reason : unknown ) => void ;
911 private timeoutId ?: NodeJS . Timeout ;
1012
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+ ) {
1217 let resolveFn : ( value : T ) => void ;
1318 let rejectFn : ( reason ?: unknown ) => void ;
1419
@@ -24,12 +29,12 @@ export class DeferredPromise<T> extends Promise<T> {
2429
2530 if ( timeout !== undefined ) {
2631 this . timeoutId = setTimeout ( ( ) => {
27- this . reject ( new Error ( "Promise timed out" ) ) ;
32+ onTimeout ?. ( this . resolve , this . reject ) ;
2833 } , timeout ) ;
2934 }
3035
31- if ( resolver ) {
32- resolver (
36+ if ( executor ) {
37+ executor (
3338 ( value : T ) => {
3439 if ( this . timeoutId ) clearTimeout ( this . timeoutId ) ;
3540 this . resolve ( value ) ;
@@ -42,7 +47,7 @@ export class DeferredPromise<T> extends Promise<T> {
4247 }
4348 }
4449
45- static fromPromise < T > ( promise : Promise < T > , options : DeferredPromiseOptions = { } ) : DeferredPromise < T > {
50+ static fromPromise < T > ( promise : Promise < T > , options : DeferredPromiseOptions < T > = { } ) : DeferredPromise < T > {
4651 return new DeferredPromise < T > ( ( resolve , reject ) => {
4752 promise
4853 . then ( ( value ) => {
@@ -51,6 +56,6 @@ export class DeferredPromise<T> extends Promise<T> {
5156 . catch ( ( reason ) => {
5257 reject ( reason as Error ) ;
5358 } ) ;
54- } , options . timeout ) ;
59+ } , options ) ;
5560 }
5661}
0 commit comments