export function debouncePromise < T extends unknown [ ] > ( fn , delay , onError ) { let timeout ; let promiseInFly ; let callbackPending ; return function debounced ( ... args ) { if ( promiseInFly ) { callbackPending = ( ) => { debounced ( ... args ) ; callbackPending = undefined ; } ; } else { if ( timeout ) clearTimeout ( timeout ) ; timeout = setTimeout ( ( ) => { timeout = undefined ; promiseInFly = fn ( ... args ) . catch ( onError ) . finally ( ( ) => { promiseInFly = undefined ; if ( callbackPending ) callbackPending ( ) ; } ) ; } , delay ) ; } } ; }