From 1bad669b0fe73713d126f87b7a4f4ab96d7651fd Mon Sep 17 00:00:00 2001 From: Snickbit Date: Fri, 14 Apr 2023 18:17:13 -0400 Subject: [PATCH] feat: create debounceAsync helper --- packages/utilities/src/functions.ts | 34 +++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/packages/utilities/src/functions.ts b/packages/utilities/src/functions.ts index 0bc47191..9a8ca62e 100644 --- a/packages/utilities/src/functions.ts +++ b/packages/utilities/src/functions.ts @@ -131,3 +131,37 @@ export function debounce) => ReturnType>(fn }, delay) } } + +/** + * Debounce a function that returns a promise + * @category Functions + */ +export function debounceAsync) => Promise>>(fn: F, delay = 50) { + let timeoutId: ReturnType + const pending: {resolve(value: unknown): void; reject(reason?: any): void}[] = [] + return (...args: Parameters) => new Promise((resolve, reject) => { + clearTimeout(timeoutId) + timeoutId = setTimeout(() => { + const currentPending = [...pending] + pending.length = 0 + Promise.resolve(fn.apply(this, args)).then(data => { + for (const {resolve} of currentPending) { + resolve(data) + } + }, + error => { + for (const {reject} of currentPending) { + reject(error) + } + }) + }, delay) + pending.push({resolve, reject}) + }) +} + +/** + * Debounce a function that returns a promise + * @alias debounceAsync + * @category Functions + */ +export const debouncePromise = debounceAsync