feat(core-utils): CB-1068 throttleAsync

This commit is contained in:
Wroud
2021-06-30 14:56:11 +03:00
parent 7949b1b880
commit 3f258c0d7d
@@ -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);
}
};
}