Path: blob/master/src/packages/util/async-debounce-throttle.ts
1447 views
/*1I couldn't find a good npm library to debounce an async function, but this2code from GPT-4o works well.34AUTHOR: GPT-4o56*/78/*9The regular lodash debounce function does not return a promise, but you10can create your own wrapper to handle this.1112### Key Points:13141. **Promise Wrapping**: Use a promise to ensure `await bar()` doesn't resolve until15after the actual function executes.16172. **Queue Maintenance**: Utilize a queue (`resolveQueue`) to store and resolve18promises after the debounced function executes.19203. **Custom Debounce Wrapper**: The `debouncePromise` function handles the21integration of promises with `lodash` debounce.22*/2324import {25debounce,26throttle,27type DebounceSettings,28type ThrottleSettings,29} from "lodash";3031export function asyncDebounce(32func: (...args: any[]) => Promise<any>,33wait: number,34options?: DebounceSettings,35): (...args: any[]) => Promise<any> {36let resolveQueue: Array<() => void> = [];3738const debounced = debounce(39async (...args: any[]) => {40await func(...args);41// Resolve all stored promises42resolveQueue.forEach((resolve) => resolve());43resolveQueue = [];44},45wait,46options,47);4849return (...args: any[]) =>50new Promise<void>((resolve) => {51resolveQueue.push(resolve);52debounced(...args);53});54}5556export function asyncThrottle(57func: (...args: any[]) => Promise<any>,58wait: number,59options?: ThrottleSettings,60): (...args: any[]) => Promise<any> {61let resolveQueue: Array<() => void> = [];6263const throttled = throttle(64async (...args: any[]) => {65await func(...args);66// Resolve all stored promises67resolveQueue.forEach((resolve) => resolve());68resolveQueue = [];69},70wait,71options,72);7374return (...args: any[]) =>75new Promise<void>((resolve) => {76resolveQueue.push(resolve);77throttled(...args);78});79}808182