@@ -90,36 +90,19 @@ export function debounce<Input extends any[], Output>(
9090 cb : ( ...args : Input ) => Output | Promise < Output > ,
9191 delay : number = 0
9292) : ( ...args : Input ) => Promise < Output > {
93- let timeout : Timeout | undefined
94- let promise : Promise < Output > | undefined
95-
96- return ( ...args : Input ) => {
97- timeout ?. refresh ( )
98-
99- return ( promise ??= new Promise < Output > ( ( resolve , reject ) => {
100- timeout = new Timeout ( delay )
101- timeout . onCompletion ( async ( ) => {
102- timeout = promise = undefined
103- try {
104- resolve ( await cb ( ...args ) )
105- } catch ( err ) {
106- reject ( err )
107- }
108- } )
109- } ) )
110- }
93+ return cancellableDebounce ( cb , delay ) . promise
11194}
11295
11396/**
11497 *
11598 * Similar to {@link debounce}, but allows the function to be cancelled and allow callbacks to pass function parameters.
11699 */
117- export function cancellableDebounce < T , U extends any [ ] > (
118- cb : ( ...args : U ) => T | Promise < T > ,
100+ export function cancellableDebounce < Input extends any [ ] , Output > (
101+ cb : ( ...args : Input ) => Output | Promise < Output > ,
119102 delay : number = 0
120- ) : { promise : ( ...args : U ) => Promise < T > ; cancel : ( ) => void } {
103+ ) : { promise : ( ...args : Input ) => Promise < Output > ; cancel : ( ) => void } {
121104 let timeout : Timeout | undefined
122- let promise : Promise < T > | undefined
105+ let promise : Promise < Output > | undefined
123106
124107 const cancel = ( ) : void => {
125108 if ( timeout ) {
@@ -130,7 +113,21 @@ export function cancellableDebounce<T, U extends any[]>(
130113 }
131114
132115 return {
133- promise : debounce ( cb , delay ) ,
116+ promise : ( ...args : Input ) => {
117+ timeout ?. refresh ( )
118+
119+ return ( promise ??= new Promise < Output > ( ( resolve , reject ) => {
120+ timeout = new Timeout ( delay )
121+ timeout . onCompletion ( async ( ) => {
122+ timeout = promise = undefined
123+ try {
124+ resolve ( await cb ( ...args ) )
125+ } catch ( err ) {
126+ reject ( err )
127+ }
128+ } )
129+ } ) )
130+ } ,
134131 cancel : cancel ,
135132 }
136133}
0 commit comments