mirror of
https://github.com/dbeaver/cloudbeaver.git
synced 2026-09-24 16:04:36 +08:00
feat(core-utils): CB-1068 throttleAsync
This commit is contained in:
@@ -6,6 +6,8 @@
|
||||
* you may not use this file except in compliance with the License.
|
||||
*/
|
||||
|
||||
type ThrottleAsync<TResult, TArguments extends any[]> = (...args: TArguments) => Promise<TResult>;
|
||||
|
||||
export function throttle<T extends (...args: any[]) => void | Promise<void>>(f: T, delay: number): T {
|
||||
let throttle = false;
|
||||
let pending = false;
|
||||
@@ -38,3 +40,52 @@ export function throttle<T extends (...args: any[]) => void | Promise<void>>(f:
|
||||
}
|
||||
} as T;
|
||||
}
|
||||
|
||||
export function throttleAsync<
|
||||
TResult,
|
||||
TArguments extends any[],
|
||||
T extends (...args: TArguments) => Promise<TResult>
|
||||
>(f: T, delay: number): ThrottleAsync<TResult, TArguments> {
|
||||
let throttle = false;
|
||||
let _resolve: ((result: TResult) => void) | null = null;
|
||||
let _reject: ((reason?: any) => void) | null = null;
|
||||
let functionArgs: TArguments | null = null;
|
||||
let thisObject: any;
|
||||
|
||||
return async function exec(this: any, ...args: TArguments): Promise<TResult> {
|
||||
if (throttle) {
|
||||
functionArgs = args;
|
||||
thisObject = this;
|
||||
|
||||
if (_reject) {
|
||||
_reject();
|
||||
}
|
||||
|
||||
return new Promise<TResult>((resolve, reject) => {
|
||||
_resolve = resolve;
|
||||
_reject = reject;
|
||||
});
|
||||
}
|
||||
|
||||
throttle = true;
|
||||
|
||||
try {
|
||||
return f.apply(this, args);
|
||||
} finally {
|
||||
setTimeout(() => {
|
||||
throttle = false;
|
||||
|
||||
if (functionArgs) {
|
||||
f.apply(thisObject, functionArgs)
|
||||
.then(_resolve)
|
||||
.catch(_reject);
|
||||
|
||||
_resolve = null;
|
||||
_reject = null;
|
||||
thisObject = null;
|
||||
functionArgs = null;
|
||||
}
|
||||
}, delay);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user