Skip to content

Commit

Permalink
fix(esl-utils): debounced promise return
Browse files Browse the repository at this point in the history
  • Loading branch information
fshovchko committed Jul 4, 2024
1 parent 038736c commit a054834
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 4 deletions.
10 changes: 8 additions & 2 deletions src/modules/esl-utils/async/debounce.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,14 @@ import {createDeferred} from './promise/defered';
import type {AnyToAnyFnSignature} from '../misc/functions';
import type {Deferred} from './promise/defered';

type UnwrapPromise<T> = T extends Promise<infer U> ? UnwrapPromise<U> : T;

/** Debounced<F> is a function wrapper type for a function decorated via debounce */
export interface Debounced<F extends AnyToAnyFnSignature> {
/** Debounced method signature */
(...args: Parameters<F>): void;
(...args: Parameters<F>): ReturnType<F> extends Promise<any>
? Promise<UnwrapPromise<ReturnType<F>>>
: ReturnType<F> | void;
/** Promise of deferred function call */
promise: Promise<ReturnType<F> | void>;
/** Cancel debounced call */
Expand All @@ -27,7 +31,7 @@ export function debounce<F extends AnyToAnyFnSignature>(fn: F, wait = 10, thisAr
let timeout: number | null = null;
let deferred: Deferred<ReturnType<F>> | null = null;

function debouncedSubject(...args: any[]): void {
function debouncedSubject(...args: any[]): Promise<ReturnType<F> | void> {
deferred = deferred || createDeferred();
(typeof timeout === 'number') && clearTimeout(timeout);
timeout = window.setTimeout(() => {
Expand All @@ -37,7 +41,9 @@ export function debounce<F extends AnyToAnyFnSignature>(fn: F, wait = 10, thisAr
deferred && deferred.resolve(result);
deferred = null;
}, wait);
return deferred.promise;
}

function cancel(): void {
(typeof timeout === 'number') && clearTimeout(timeout);
timeout = null;
Expand Down
3 changes: 1 addition & 2 deletions src/modules/esl-utils/async/test/debounce.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,12 @@ describe('async/debounce', () => {
const fn = jest.fn();
const debounced = debounce(fn, 50);

expect(debounced()).toBeUndefined();
debounced();
jest.advanceTimersByTime(25);
expect(debounced()).toBeUndefined();
expect(fn).toBeCalledTimes(0);
jest.advanceTimersByTime(50);
expect(fn).toBeCalledTimes(1);
expect(debounced()).resolves.toBeUndefined();
});

test('call context', () => {
Expand Down

0 comments on commit a054834

Please sign in to comment.