@tanstack/pacer 0.5.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/async-debouncer.cjs +24 -13
- package/dist/cjs/async-debouncer.cjs.map +1 -1
- package/dist/cjs/async-debouncer.d.cts +49 -7
- package/dist/cjs/async-queuer.cjs +83 -114
- package/dist/cjs/async-queuer.cjs.map +1 -1
- package/dist/cjs/async-queuer.d.cts +79 -50
- package/dist/cjs/async-rate-limiter.cjs +20 -9
- package/dist/cjs/async-rate-limiter.cjs.map +1 -1
- package/dist/cjs/async-rate-limiter.d.cts +53 -3
- package/dist/cjs/async-throttler.cjs +24 -13
- package/dist/cjs/async-throttler.cjs.map +1 -1
- package/dist/cjs/async-throttler.d.cts +48 -6
- package/dist/cjs/types.d.cts +1 -0
- package/dist/esm/async-debouncer.d.ts +49 -7
- package/dist/esm/async-debouncer.js +24 -13
- package/dist/esm/async-debouncer.js.map +1 -1
- package/dist/esm/async-queuer.d.ts +79 -50
- package/dist/esm/async-queuer.js +83 -114
- package/dist/esm/async-queuer.js.map +1 -1
- package/dist/esm/async-rate-limiter.d.ts +53 -3
- package/dist/esm/async-rate-limiter.js +20 -9
- package/dist/esm/async-rate-limiter.js.map +1 -1
- package/dist/esm/async-throttler.d.ts +48 -6
- package/dist/esm/async-throttler.js +24 -13
- package/dist/esm/async-throttler.js.map +1 -1
- package/dist/esm/types.d.ts +1 -0
- package/package.json +1 -1
- package/src/async-debouncer.ts +66 -16
- package/src/async-queuer.ts +180 -169
- package/src/async-rate-limiter.ts +70 -12
- package/src/async-throttler.ts +66 -16
- package/src/types.ts +3 -0
|
@@ -4,12 +4,6 @@ const utils = require("./utils.cjs");
|
|
|
4
4
|
const defaultOptions = {
|
|
5
5
|
enabled: true,
|
|
6
6
|
leading: false,
|
|
7
|
-
onError: () => {
|
|
8
|
-
},
|
|
9
|
-
onSettled: () => {
|
|
10
|
-
},
|
|
11
|
-
onSuccess: () => {
|
|
12
|
-
},
|
|
13
7
|
trailing: true,
|
|
14
8
|
wait: 0
|
|
15
9
|
};
|
|
@@ -26,7 +20,8 @@ class AsyncDebouncer {
|
|
|
26
20
|
this._timeoutId = null;
|
|
27
21
|
this._options = {
|
|
28
22
|
...defaultOptions,
|
|
29
|
-
...initialOptions
|
|
23
|
+
...initialOptions,
|
|
24
|
+
throwOnError: initialOptions.throwOnError ?? !initialOptions.onError
|
|
30
25
|
};
|
|
31
26
|
}
|
|
32
27
|
/**
|
|
@@ -49,7 +44,7 @@ class AsyncDebouncer {
|
|
|
49
44
|
* Returns the current debouncer enabled state
|
|
50
45
|
*/
|
|
51
46
|
getEnabled() {
|
|
52
|
-
return utils.parseFunctionOrValue(this._options.enabled, this);
|
|
47
|
+
return !!utils.parseFunctionOrValue(this._options.enabled, this);
|
|
53
48
|
}
|
|
54
49
|
/**
|
|
55
50
|
* Returns the current debouncer wait state
|
|
@@ -58,8 +53,18 @@ class AsyncDebouncer {
|
|
|
58
53
|
return utils.parseFunctionOrValue(this._options.wait, this);
|
|
59
54
|
}
|
|
60
55
|
/**
|
|
61
|
-
* Attempts to execute the debounced function
|
|
62
|
-
* If a call is already in progress, it will be queued
|
|
56
|
+
* Attempts to execute the debounced function.
|
|
57
|
+
* If a call is already in progress, it will be queued.
|
|
58
|
+
*
|
|
59
|
+
* Error Handling:
|
|
60
|
+
* - If the debounced function throws and no `onError` handler is configured,
|
|
61
|
+
* the error will be thrown from this method.
|
|
62
|
+
* - If an `onError` handler is configured, errors will be caught and passed to the handler,
|
|
63
|
+
* and this method will return undefined.
|
|
64
|
+
* - The error state can be checked using `getErrorCount()` and `getIsExecuting()`.
|
|
65
|
+
*
|
|
66
|
+
* @returns A promise that resolves with the function's return value, or undefined if an error occurred and was handled by onError
|
|
67
|
+
* @throws The error from the debounced function if no onError handler is configured
|
|
63
68
|
*/
|
|
64
69
|
async maybeExecute(...args) {
|
|
65
70
|
this._cancel();
|
|
@@ -83,22 +88,28 @@ class AsyncDebouncer {
|
|
|
83
88
|
});
|
|
84
89
|
}
|
|
85
90
|
async executeFunction(...args) {
|
|
91
|
+
var _a, _b, _c, _d, _e, _f;
|
|
86
92
|
if (!this.getEnabled()) return void 0;
|
|
87
93
|
this._abortController = new AbortController();
|
|
88
94
|
try {
|
|
89
95
|
this._isExecuting = true;
|
|
90
96
|
this._lastResult = await this.fn(...args);
|
|
91
97
|
this._successCount++;
|
|
92
|
-
this._options.onSuccess(this._lastResult, this);
|
|
98
|
+
(_b = (_a = this._options).onSuccess) == null ? void 0 : _b.call(_a, this._lastResult, this);
|
|
93
99
|
} catch (error) {
|
|
94
100
|
this._errorCount++;
|
|
95
|
-
this._options.onError(error, this);
|
|
101
|
+
(_d = (_c = this._options).onError) == null ? void 0 : _d.call(_c, error, this);
|
|
102
|
+
if (this._options.throwOnError) {
|
|
103
|
+
throw error;
|
|
104
|
+
} else {
|
|
105
|
+
console.error(error);
|
|
106
|
+
}
|
|
96
107
|
} finally {
|
|
97
108
|
this._isExecuting = false;
|
|
98
109
|
this._isPending = false;
|
|
99
110
|
this._settleCount++;
|
|
100
111
|
this._abortController = null;
|
|
101
|
-
this._options.onSettled(this);
|
|
112
|
+
(_f = (_e = this._options).onSettled) == null ? void 0 : _f.call(_e, this);
|
|
102
113
|
}
|
|
103
114
|
return this._lastResult;
|
|
104
115
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"async-debouncer.cjs","sources":["../../src/async-debouncer.ts"],"sourcesContent":["import { parseFunctionOrValue } from './utils'\nimport type { AnyAsyncFunction } from './types'\n\n/**\n * Options for configuring an async debounced function\n */\nexport interface AsyncDebouncerOptions<TFn extends AnyAsyncFunction> {\n /**\n * Whether the debouncer is enabled. When disabled, maybeExecute will not trigger any executions.\n * Can be a boolean or a function that returns a boolean.\n * Defaults to true.\n */\n enabled?: boolean | ((debouncer: AsyncDebouncer<TFn>) => boolean)\n /**\n * Whether to execute on the leading edge of the timeout.\n * Defaults to false.\n */\n leading?: boolean\n /**\n * Optional error handler for when the debounced function throws\n */\n onError?: (error: unknown, debouncer: AsyncDebouncer<TFn>) => void\n /**\n * Optional callback to call when the debounced function is executed\n */\n onSettled?: (debouncer: AsyncDebouncer<TFn>) => void\n /**\n * Optional callback to call when the debounced function is executed\n */\n onSuccess?: (result: ReturnType<TFn>, debouncer: AsyncDebouncer<TFn>) => void\n /**\n * Whether to execute on the trailing edge of the timeout.\n * Defaults to true.\n */\n trailing?: boolean\n /**\n * Delay in milliseconds to wait after the last call before executing.\n * Can be a number or a function that returns a number.\n * Defaults to 0ms\n */\n wait: number | ((debouncer: AsyncDebouncer<TFn>) => number)\n}\n\nconst defaultOptions: Required<AsyncDebouncerOptions<any>> = {\n enabled: true,\n leading: false,\n onError: () => {},\n onSettled: () => {},\n onSuccess: () => {},\n trailing: true,\n wait: 0,\n}\n\n/**\n * A class that creates an async debounced function.\n *\n * Debouncing ensures that a function is only executed after a specified delay has passed since its last invocation.\n * Each new invocation resets the delay timer. This is useful for handling frequent events like window resizing\n * or input changes where you only want to execute the handler after the events have stopped occurring.\n *\n * Unlike throttling which allows execution at regular intervals, debouncing prevents any execution until\n * the function stops being called for the specified delay period.\n *\n * Unlike the non-async Debouncer, this async version supports returning values from the debounced function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the debounced function.\n *\n * @example\n * ```ts\n * const asyncDebouncer = new AsyncDebouncer(async (value: string) => {\n * const results = await searchAPI(value);\n * return results; // Return value is preserved\n * }, { wait: 500 });\n *\n * // Called on each keystroke but only executes after 500ms of no typing\n * // Returns the API response directly\n * const results = await asyncDebouncer.maybeExecute(inputElement.value);\n * ```\n */\nexport class AsyncDebouncer<TFn extends AnyAsyncFunction> {\n private _abortController: AbortController | null = null\n private _canLeadingExecute = true\n private _errorCount = 0\n private _isExecuting = false\n private _isPending = false\n private _lastArgs: Parameters<TFn> | undefined\n private _lastResult: ReturnType<TFn> | undefined\n private _options: Required<AsyncDebouncerOptions<TFn>>\n private _settleCount = 0\n private _successCount = 0\n private _timeoutId: NodeJS.Timeout | null = null\n\n constructor(\n private fn: TFn,\n initialOptions: AsyncDebouncerOptions<TFn>,\n ) {\n this._options = {\n ...defaultOptions,\n ...initialOptions,\n }\n }\n\n /**\n * Updates the debouncer options\n * Returns the new options state\n */\n setOptions(newOptions: Partial<AsyncDebouncerOptions<TFn>>): void {\n this._options = { ...this._options, ...newOptions }\n\n // End the pending state if the debouncer is disabled\n if (!this._options.enabled) {\n this._isPending = false\n }\n }\n\n /**\n * Returns the current debouncer options\n */\n getOptions(): Required<AsyncDebouncerOptions<TFn>> {\n return this._options\n }\n\n /**\n * Returns the current debouncer enabled state\n */\n getEnabled(): boolean {\n return parseFunctionOrValue(this._options.enabled, this)\n }\n\n /**\n * Returns the current debouncer wait state\n */\n getWait(): number {\n return parseFunctionOrValue(this._options.wait, this)\n }\n\n /**\n * Attempts to execute the debounced function\n * If a call is already in progress, it will be queued\n */\n async maybeExecute(\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> {\n this._cancel()\n this._lastArgs = args\n\n // Handle leading execution\n if (this._options.leading && this._canLeadingExecute) {\n this._canLeadingExecute = false\n await this.executeFunction(...args)\n return this._lastResult\n }\n\n // Handle trailing execution\n if (this._options.trailing) {\n this._isPending = true\n }\n\n return new Promise((resolve) => {\n this._timeoutId = setTimeout(async () => {\n // Execute trailing if enabled\n if (this._options.trailing && this._lastArgs) {\n await this.executeFunction(...this._lastArgs)\n }\n\n // Reset state and resolve\n this._canLeadingExecute = true\n resolve(this._lastResult)\n }, this.getWait())\n })\n }\n\n private async executeFunction(\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> {\n if (!this.getEnabled()) return undefined\n this._abortController = new AbortController()\n try {\n this._isExecuting = true\n this._lastResult = await this.fn(...args) // EXECUTE!\n this._successCount++\n this._options.onSuccess(this._lastResult!, this)\n } catch (error) {\n this._errorCount++\n this._options.onError(error, this)\n } finally {\n this._isExecuting = false\n this._isPending = false\n this._settleCount++\n this._abortController = null\n this._options.onSettled(this)\n }\n return this._lastResult\n }\n\n /**\n * Cancel without resetting _canLeadingExecute\n */\n private _cancel(): void {\n if (this._timeoutId) {\n clearTimeout(this._timeoutId)\n this._timeoutId = null\n }\n if (this._abortController) {\n this._abortController.abort()\n this._abortController = null\n }\n this._lastArgs = undefined\n this._isPending = false\n this._isExecuting = false\n }\n\n /**\n * Cancels any pending execution or aborts any execution in progress\n */\n cancel(): void {\n this._canLeadingExecute = true\n this._cancel()\n }\n\n /**\n * Returns the last result of the debounced function\n */\n getLastResult(): ReturnType<TFn> | undefined {\n return this._lastResult\n }\n\n /**\n * Returns the number of times the function has been executed successfully\n */\n getSuccessCount(): number {\n return this._successCount\n }\n\n /**\n * Returns the number of times the function has settled (completed or errored)\n */\n getSettleCount(): number {\n return this._settleCount\n }\n\n /**\n * Returns the number of times the function has errored\n */\n getErrorCount(): number {\n return this._errorCount\n }\n\n /**\n * Returns `true` if there is a pending execution queued up for trailing execution\n */\n getIsPending(): boolean {\n return this.getEnabled() && this._isPending\n }\n\n /**\n * Returns `true` if there is currently an execution in progress\n */\n getIsExecuting(): boolean {\n return this._isExecuting\n }\n}\n\n/**\n * Creates an async debounced function that delays execution until after a specified wait time.\n * The debounced function will only execute once the wait period has elapsed without any new calls.\n * If called again during the wait period, the timer resets and a new wait period begins.\n *\n * Unlike the non-async Debouncer, this async version supports returning values from the debounced function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the debounced function.\n *\n * @example\n * ```ts\n * const debounced = asyncDebounce(async (value: string) => {\n * const result = await saveToAPI(value);\n * return result; // Return value is preserved\n * }, { wait: 1000 });\n *\n * // Will only execute once, 1 second after the last call\n * // Returns the API response directly\n * const result = await debounced(\"third\");\n * ```\n */\nexport function asyncDebounce<TFn extends AnyAsyncFunction>(\n fn: TFn,\n initialOptions: AsyncDebouncerOptions<TFn>,\n) {\n const asyncD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AA;AAAA;AAAA;AAAA,EAMf,gBAA6C;AAC3C,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,kBAA0B;AACxB,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,iBAAyB;AACvB,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,gBAAwB;AACtB,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,eAAwB;AACf,WAAA,KAAK,gBAAgB,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMnC,iBAA0B;AACxB,WAAO,KAAK;AAAA,EAAA;AAEhB;AAuBgB,SAAA,cACd,IACA,gBACA;AACA,QAAM,iBAAiB,IAAI,eAAe,IAAI,cAAc;AACrD,SAAA,eAAe,aAAa,KAAK,cAAc;AACxD;;;"}
|
|
1
|
+
{"version":3,"file":"async-debouncer.cjs","sources":["../../src/async-debouncer.ts"],"sourcesContent":["import { parseFunctionOrValue } from './utils'\nimport type { AnyAsyncFunction, OptionalKeys } from './types'\n\n/**\n * Options for configuring an async debounced function\n */\nexport interface AsyncDebouncerOptions<TFn extends AnyAsyncFunction> {\n /**\n * Whether the debouncer is enabled. When disabled, maybeExecute will not trigger any executions.\n * Can be a boolean or a function that returns a boolean.\n * Defaults to true.\n */\n enabled?: boolean | ((debouncer: AsyncDebouncer<TFn>) => boolean)\n /**\n * Whether to execute on the leading edge of the timeout.\n * Defaults to false.\n */\n leading?: boolean\n /**\n * Optional error handler for when the debounced function throws.\n * If provided, the handler will be called with the error and debouncer instance.\n * This can be used alongside throwOnError - the handler will be called before any error is thrown.\n */\n onError?: (error: unknown, debouncer: AsyncDebouncer<TFn>) => void\n /**\n * Optional callback to call when the debounced function is executed\n */\n onSettled?: (debouncer: AsyncDebouncer<TFn>) => void\n /**\n * Optional callback to call when the debounced function is executed\n */\n onSuccess?: (result: ReturnType<TFn>, debouncer: AsyncDebouncer<TFn>) => void\n /**\n * Whether to throw errors when they occur.\n * Defaults to true if no onError handler is provided, false if an onError handler is provided.\n * Can be explicitly set to override these defaults.\n */\n throwOnError?: boolean\n /**\n * Whether to execute on the trailing edge of the timeout.\n * Defaults to true.\n */\n trailing?: boolean\n /**\n * Delay in milliseconds to wait after the last call before executing.\n * Can be a number or a function that returns a number.\n * Defaults to 0ms\n */\n wait: number | ((debouncer: AsyncDebouncer<TFn>) => number)\n}\n\ntype AsyncDebouncerOptionsWithOptionalCallbacks = OptionalKeys<\n AsyncDebouncerOptions<any>,\n 'onError' | 'onSettled' | 'onSuccess'\n>\n\nconst defaultOptions: AsyncDebouncerOptionsWithOptionalCallbacks = {\n enabled: true,\n leading: false,\n trailing: true,\n wait: 0,\n}\n\n/**\n * A class that creates an async debounced function.\n *\n * Debouncing ensures that a function is only executed after a specified delay has passed since its last invocation.\n * Each new invocation resets the delay timer. This is useful for handling frequent events like window resizing\n * or input changes where you only want to execute the handler after the events have stopped occurring.\n *\n * Unlike throttling which allows execution at regular intervals, debouncing prevents any execution until\n * the function stops being called for the specified delay period.\n *\n * Unlike the non-async Debouncer, this async version supports returning values from the debounced function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the debounced function.\n *\n * Error Handling:\n * - If an error occurs during execution and no `onError` handler is provided, the error will be thrown and propagate up to the caller.\n * - If an `onError` handler is provided, errors will be caught and passed to the handler instead of being thrown.\n * - The error count can be tracked using `getErrorCount()`.\n * - The debouncer maintains its state and can continue to be used after an error occurs.\n *\n * @example\n * ```ts\n * const asyncDebouncer = new AsyncDebouncer(async (value: string) => {\n * const results = await searchAPI(value);\n * return results; // Return value is preserved\n * }, {\n * wait: 500,\n * onError: (error) => {\n * console.error('Search failed:', error);\n * }\n * });\n *\n * // Called on each keystroke but only executes after 500ms of no typing\n * // Returns the API response directly\n * const results = await asyncDebouncer.maybeExecute(inputElement.value);\n * ```\n */\nexport class AsyncDebouncer<TFn extends AnyAsyncFunction> {\n private _options: AsyncDebouncerOptionsWithOptionalCallbacks\n private _abortController: AbortController | null = null\n private _canLeadingExecute = true\n private _errorCount = 0\n private _isExecuting = false\n private _isPending = false\n private _lastArgs: Parameters<TFn> | undefined\n private _lastResult: ReturnType<TFn> | undefined\n private _settleCount = 0\n private _successCount = 0\n private _timeoutId: NodeJS.Timeout | null = null\n\n constructor(\n private fn: TFn,\n initialOptions: AsyncDebouncerOptions<TFn>,\n ) {\n this._options = {\n ...defaultOptions,\n ...initialOptions,\n throwOnError: initialOptions.throwOnError ?? !initialOptions.onError,\n }\n }\n\n /**\n * Updates the debouncer options\n * Returns the new options state\n */\n setOptions(newOptions: Partial<AsyncDebouncerOptions<TFn>>): void {\n this._options = { ...this._options, ...newOptions }\n\n // End the pending state if the debouncer is disabled\n if (!this._options.enabled) {\n this._isPending = false\n }\n }\n\n /**\n * Returns the current debouncer options\n */\n getOptions(): AsyncDebouncerOptions<TFn> {\n return this._options\n }\n\n /**\n * Returns the current debouncer enabled state\n */\n getEnabled(): boolean {\n return !!parseFunctionOrValue(this._options.enabled, this)\n }\n\n /**\n * Returns the current debouncer wait state\n */\n getWait(): number {\n return parseFunctionOrValue(this._options.wait, this)\n }\n\n /**\n * Attempts to execute the debounced function.\n * If a call is already in progress, it will be queued.\n *\n * Error Handling:\n * - If the debounced function throws and no `onError` handler is configured,\n * the error will be thrown from this method.\n * - If an `onError` handler is configured, errors will be caught and passed to the handler,\n * and this method will return undefined.\n * - The error state can be checked using `getErrorCount()` and `getIsExecuting()`.\n *\n * @returns A promise that resolves with the function's return value, or undefined if an error occurred and was handled by onError\n * @throws The error from the debounced function if no onError handler is configured\n */\n async maybeExecute(\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> {\n this._cancel()\n this._lastArgs = args\n\n // Handle leading execution\n if (this._options.leading && this._canLeadingExecute) {\n this._canLeadingExecute = false\n await this.executeFunction(...args)\n return this._lastResult\n }\n\n // Handle trailing execution\n if (this._options.trailing) {\n this._isPending = true\n }\n\n return new Promise((resolve) => {\n this._timeoutId = setTimeout(async () => {\n // Execute trailing if enabled\n if (this._options.trailing && this._lastArgs) {\n await this.executeFunction(...this._lastArgs)\n }\n\n // Reset state and resolve\n this._canLeadingExecute = true\n resolve(this._lastResult)\n }, this.getWait())\n })\n }\n\n private async executeFunction(\n ...args: Parameters<TFn>\n ): Promise<ReturnType<TFn> | undefined> {\n if (!this.getEnabled()) return undefined\n this._abortController = new AbortController()\n try {\n this._isExecuting = true\n this._lastResult = await this.fn(...args) // EXECUTE!\n this._successCount++\n this._options.onSuccess?.(this._lastResult!, this)\n } catch (error) {\n this._errorCount++\n this._options.onError?.(error, this)\n if (this._options.throwOnError) {\n throw error\n } else {\n console.error(error)\n }\n } finally {\n this._isExecuting = false\n this._isPending = false\n this._settleCount++\n this._abortController = null\n this._options.onSettled?.(this)\n }\n return this._lastResult\n }\n\n /**\n * Cancel without resetting _canLeadingExecute\n */\n private _cancel(): void {\n if (this._timeoutId) {\n clearTimeout(this._timeoutId)\n this._timeoutId = null\n }\n if (this._abortController) {\n this._abortController.abort()\n this._abortController = null\n }\n this._lastArgs = undefined\n this._isPending = false\n this._isExecuting = false\n }\n\n /**\n * Cancels any pending execution or aborts any execution in progress\n */\n cancel(): void {\n this._canLeadingExecute = true\n this._cancel()\n }\n\n /**\n * Returns the last result of the debounced function\n */\n getLastResult(): ReturnType<TFn> | undefined {\n return this._lastResult\n }\n\n /**\n * Returns the number of times the function has been executed successfully\n */\n getSuccessCount(): number {\n return this._successCount\n }\n\n /**\n * Returns the number of times the function has settled (completed or errored)\n */\n getSettleCount(): number {\n return this._settleCount\n }\n\n /**\n * Returns the number of times the function has errored\n */\n getErrorCount(): number {\n return this._errorCount\n }\n\n /**\n * Returns `true` if there is a pending execution queued up for trailing execution\n */\n getIsPending(): boolean {\n return this.getEnabled() && this._isPending\n }\n\n /**\n * Returns `true` if there is currently an execution in progress\n */\n getIsExecuting(): boolean {\n return this._isExecuting\n }\n}\n\n/**\n * Creates an async debounced function that delays execution until after a specified wait time.\n * The debounced function will only execute once the wait period has elapsed without any new calls.\n * If called again during the wait period, the timer resets and a new wait period begins.\n *\n * Unlike the non-async Debouncer, this async version supports returning values from the debounced function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the debounced function.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and debouncer instance\n * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown\n * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed\n * - The error state can be checked using the underlying AsyncDebouncer instance\n * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown\n *\n * @example\n * ```ts\n * const debounced = asyncDebounce(async (value: string) => {\n * const result = await saveToAPI(value);\n * return result; // Return value is preserved\n * }, {\n * wait: 1000,\n * onError: (error) => {\n * console.error('API call failed:', error);\n * },\n * throwOnError: true // Will both log the error and throw it\n * });\n *\n * // Will only execute once, 1 second after the last call\n * // Returns the API response directly\n * const result = await debounced(\"third\");\n * ```\n */\nexport function asyncDebounce<TFn extends AnyAsyncFunction>(\n fn: TFn,\n initialOptions: AsyncDebouncerOptions<TFn>,\n) {\n const asyncDebouncer = new AsyncDebouncer(fn, initialOptions)\n return asyncDebouncer.maybeExecute.bind(asyncDebouncer)\n}\n"],"names":["parseFunctionOrValue"],"mappings":";;;AAwDA,MAAM,iBAA6D;AAAA,EACjE,SAAS;AAAA,EACT,SAAS;AAAA,EACT,UAAU;AAAA,EACV,MAAM;AACR;AAuCO,MAAM,eAA6C;AAAA,EAaxD,YACU,IACR,gBACA;AAFQ,SAAA,KAAA;AAZV,SAAQ,mBAA2C;AACnD,SAAQ,qBAAqB;AAC7B,SAAQ,cAAc;AACtB,SAAQ,eAAe;AACvB,SAAQ,aAAa;AAGrB,SAAQ,eAAe;AACvB,SAAQ,gBAAgB;AACxB,SAAQ,aAAoC;AAM1C,SAAK,WAAW;AAAA,MACd,GAAG;AAAA,MACH,GAAG;AAAA,MACH,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MnC,iBAA0B;AACxB,WAAO,KAAK;AAAA,EAAA;AAEhB;AAoCgB,SAAA,cACd,IACA,gBACA;AACA,QAAM,iBAAiB,IAAI,eAAe,IAAI,cAAc;AACrD,SAAA,eAAe,aAAa,KAAK,cAAc;AACxD;;;"}
|
|
@@ -15,7 +15,9 @@ export interface AsyncDebouncerOptions<TFn extends AnyAsyncFunction> {
|
|
|
15
15
|
*/
|
|
16
16
|
leading?: boolean;
|
|
17
17
|
/**
|
|
18
|
-
* Optional error handler for when the debounced function throws
|
|
18
|
+
* Optional error handler for when the debounced function throws.
|
|
19
|
+
* If provided, the handler will be called with the error and debouncer instance.
|
|
20
|
+
* This can be used alongside throwOnError - the handler will be called before any error is thrown.
|
|
19
21
|
*/
|
|
20
22
|
onError?: (error: unknown, debouncer: AsyncDebouncer<TFn>) => void;
|
|
21
23
|
/**
|
|
@@ -26,6 +28,12 @@ export interface AsyncDebouncerOptions<TFn extends AnyAsyncFunction> {
|
|
|
26
28
|
* Optional callback to call when the debounced function is executed
|
|
27
29
|
*/
|
|
28
30
|
onSuccess?: (result: ReturnType<TFn>, debouncer: AsyncDebouncer<TFn>) => void;
|
|
31
|
+
/**
|
|
32
|
+
* Whether to throw errors when they occur.
|
|
33
|
+
* Defaults to true if no onError handler is provided, false if an onError handler is provided.
|
|
34
|
+
* Can be explicitly set to override these defaults.
|
|
35
|
+
*/
|
|
36
|
+
throwOnError?: boolean;
|
|
29
37
|
/**
|
|
30
38
|
* Whether to execute on the trailing edge of the timeout.
|
|
31
39
|
* Defaults to true.
|
|
@@ -52,12 +60,23 @@ export interface AsyncDebouncerOptions<TFn extends AnyAsyncFunction> {
|
|
|
52
60
|
* making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call
|
|
53
61
|
* instead of setting the result on a state variable from within the debounced function.
|
|
54
62
|
*
|
|
63
|
+
* Error Handling:
|
|
64
|
+
* - If an error occurs during execution and no `onError` handler is provided, the error will be thrown and propagate up to the caller.
|
|
65
|
+
* - If an `onError` handler is provided, errors will be caught and passed to the handler instead of being thrown.
|
|
66
|
+
* - The error count can be tracked using `getErrorCount()`.
|
|
67
|
+
* - The debouncer maintains its state and can continue to be used after an error occurs.
|
|
68
|
+
*
|
|
55
69
|
* @example
|
|
56
70
|
* ```ts
|
|
57
71
|
* const asyncDebouncer = new AsyncDebouncer(async (value: string) => {
|
|
58
72
|
* const results = await searchAPI(value);
|
|
59
73
|
* return results; // Return value is preserved
|
|
60
|
-
* }, {
|
|
74
|
+
* }, {
|
|
75
|
+
* wait: 500,
|
|
76
|
+
* onError: (error) => {
|
|
77
|
+
* console.error('Search failed:', error);
|
|
78
|
+
* }
|
|
79
|
+
* });
|
|
61
80
|
*
|
|
62
81
|
* // Called on each keystroke but only executes after 500ms of no typing
|
|
63
82
|
* // Returns the API response directly
|
|
@@ -66,6 +85,7 @@ export interface AsyncDebouncerOptions<TFn extends AnyAsyncFunction> {
|
|
|
66
85
|
*/
|
|
67
86
|
export declare class AsyncDebouncer<TFn extends AnyAsyncFunction> {
|
|
68
87
|
private fn;
|
|
88
|
+
private _options;
|
|
69
89
|
private _abortController;
|
|
70
90
|
private _canLeadingExecute;
|
|
71
91
|
private _errorCount;
|
|
@@ -73,7 +93,6 @@ export declare class AsyncDebouncer<TFn extends AnyAsyncFunction> {
|
|
|
73
93
|
private _isPending;
|
|
74
94
|
private _lastArgs;
|
|
75
95
|
private _lastResult;
|
|
76
|
-
private _options;
|
|
77
96
|
private _settleCount;
|
|
78
97
|
private _successCount;
|
|
79
98
|
private _timeoutId;
|
|
@@ -86,7 +105,7 @@ export declare class AsyncDebouncer<TFn extends AnyAsyncFunction> {
|
|
|
86
105
|
/**
|
|
87
106
|
* Returns the current debouncer options
|
|
88
107
|
*/
|
|
89
|
-
getOptions():
|
|
108
|
+
getOptions(): AsyncDebouncerOptions<TFn>;
|
|
90
109
|
/**
|
|
91
110
|
* Returns the current debouncer enabled state
|
|
92
111
|
*/
|
|
@@ -96,8 +115,18 @@ export declare class AsyncDebouncer<TFn extends AnyAsyncFunction> {
|
|
|
96
115
|
*/
|
|
97
116
|
getWait(): number;
|
|
98
117
|
/**
|
|
99
|
-
* Attempts to execute the debounced function
|
|
100
|
-
* If a call is already in progress, it will be queued
|
|
118
|
+
* Attempts to execute the debounced function.
|
|
119
|
+
* If a call is already in progress, it will be queued.
|
|
120
|
+
*
|
|
121
|
+
* Error Handling:
|
|
122
|
+
* - If the debounced function throws and no `onError` handler is configured,
|
|
123
|
+
* the error will be thrown from this method.
|
|
124
|
+
* - If an `onError` handler is configured, errors will be caught and passed to the handler,
|
|
125
|
+
* and this method will return undefined.
|
|
126
|
+
* - The error state can be checked using `getErrorCount()` and `getIsExecuting()`.
|
|
127
|
+
*
|
|
128
|
+
* @returns A promise that resolves with the function's return value, or undefined if an error occurred and was handled by onError
|
|
129
|
+
* @throws The error from the debounced function if no onError handler is configured
|
|
101
130
|
*/
|
|
102
131
|
maybeExecute(...args: Parameters<TFn>): Promise<ReturnType<TFn> | undefined>;
|
|
103
132
|
private executeFunction;
|
|
@@ -143,12 +172,25 @@ export declare class AsyncDebouncer<TFn extends AnyAsyncFunction> {
|
|
|
143
172
|
* making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call
|
|
144
173
|
* instead of setting the result on a state variable from within the debounced function.
|
|
145
174
|
*
|
|
175
|
+
* Error Handling:
|
|
176
|
+
* - If an `onError` handler is provided, it will be called with the error and debouncer instance
|
|
177
|
+
* - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
|
|
178
|
+
* - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
|
|
179
|
+
* - The error state can be checked using the underlying AsyncDebouncer instance
|
|
180
|
+
* - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
|
|
181
|
+
*
|
|
146
182
|
* @example
|
|
147
183
|
* ```ts
|
|
148
184
|
* const debounced = asyncDebounce(async (value: string) => {
|
|
149
185
|
* const result = await saveToAPI(value);
|
|
150
186
|
* return result; // Return value is preserved
|
|
151
|
-
* }, {
|
|
187
|
+
* }, {
|
|
188
|
+
* wait: 1000,
|
|
189
|
+
* onError: (error) => {
|
|
190
|
+
* console.error('API call failed:', error);
|
|
191
|
+
* },
|
|
192
|
+
* throwOnError: true // Will both log the error and throw it
|
|
193
|
+
* });
|
|
152
194
|
*
|
|
153
195
|
* // Will only execute once, 1 second after the last call
|
|
154
196
|
* // Returns the API response directly
|
|
@@ -10,32 +10,25 @@ const defaultOptions = {
|
|
|
10
10
|
getPriority: (item) => (item == null ? void 0 : item.priority) ?? 0,
|
|
11
11
|
initialItems: [],
|
|
12
12
|
maxSize: Infinity,
|
|
13
|
-
onGetNextItem: () => {
|
|
14
|
-
},
|
|
15
|
-
onIsRunningChange: () => {
|
|
16
|
-
},
|
|
17
|
-
onItemsChange: () => {
|
|
18
|
-
},
|
|
19
|
-
onReject: () => {
|
|
20
|
-
},
|
|
21
|
-
onExpire: () => {
|
|
22
|
-
},
|
|
23
13
|
started: true,
|
|
24
14
|
wait: 0
|
|
25
15
|
};
|
|
26
16
|
class AsyncQueuer {
|
|
27
17
|
constructor(initialOptions = defaultOptions) {
|
|
28
18
|
this._activeItems = /* @__PURE__ */ new Set();
|
|
29
|
-
this.
|
|
19
|
+
this._successCount = 0;
|
|
20
|
+
this._errorCount = 0;
|
|
21
|
+
this._settledCount = 0;
|
|
30
22
|
this._rejectionCount = 0;
|
|
31
23
|
this._expirationCount = 0;
|
|
32
24
|
this._items = [];
|
|
33
25
|
this._itemTimestamps = [];
|
|
34
|
-
this._onErrorCallbacks = [];
|
|
35
|
-
this._onSettledCallbacks = [];
|
|
36
|
-
this._onSuccessCallbacks = [];
|
|
37
26
|
this._pendingTick = false;
|
|
38
|
-
this._options = {
|
|
27
|
+
this._options = {
|
|
28
|
+
...defaultOptions,
|
|
29
|
+
...initialOptions,
|
|
30
|
+
throwOnError: initialOptions.throwOnError ?? !initialOptions.onError
|
|
31
|
+
};
|
|
39
32
|
this._running = this._options.started;
|
|
40
33
|
for (let i = 0; i < this._options.initialItems.length; i++) {
|
|
41
34
|
const item = this._options.initialItems[i];
|
|
@@ -72,6 +65,7 @@ class AsyncQueuer {
|
|
|
72
65
|
* Processes items in the queuer
|
|
73
66
|
*/
|
|
74
67
|
tick() {
|
|
68
|
+
var _a, _b;
|
|
75
69
|
if (!this._running) {
|
|
76
70
|
this._pendingTick = false;
|
|
77
71
|
return;
|
|
@@ -83,26 +77,28 @@ class AsyncQueuer {
|
|
|
83
77
|
break;
|
|
84
78
|
}
|
|
85
79
|
this._activeItems.add(nextFn);
|
|
86
|
-
this._options.onItemsChange(this);
|
|
80
|
+
(_b = (_a = this._options).onItemsChange) == null ? void 0 : _b.call(_a, this);
|
|
87
81
|
(async () => {
|
|
88
|
-
|
|
82
|
+
var _a2, _b2, _c, _d, _e, _f, _g, _h;
|
|
89
83
|
let res;
|
|
90
|
-
let error;
|
|
91
84
|
try {
|
|
92
85
|
res = await nextFn();
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
86
|
+
this._successCount++;
|
|
87
|
+
(_b2 = (_a2 = this._options).onSuccess) == null ? void 0 : _b2.call(_a2, res, this);
|
|
88
|
+
} catch (error) {
|
|
89
|
+
this._errorCount++;
|
|
90
|
+
(_d = (_c = this._options).onError) == null ? void 0 : _d.call(_c, error, this);
|
|
91
|
+
if (this._options.throwOnError) {
|
|
92
|
+
throw error;
|
|
93
|
+
} else {
|
|
94
|
+
console.error(error);
|
|
95
|
+
}
|
|
96
96
|
} finally {
|
|
97
|
+
this._settledCount++;
|
|
97
98
|
this._activeItems.delete(nextFn);
|
|
98
|
-
this._options.onItemsChange(this);
|
|
99
|
-
|
|
100
|
-
if (success) {
|
|
101
|
-
this._onSuccessCallbacks.forEach((cb) => cb(res));
|
|
102
|
-
} else {
|
|
103
|
-
this._onErrorCallbacks.forEach((cb) => cb(error));
|
|
99
|
+
(_f = (_e = this._options).onItemsChange) == null ? void 0 : _f.call(_e, this);
|
|
100
|
+
(_h = (_g = this._options).onSettled) == null ? void 0 : _h.call(_g, this);
|
|
104
101
|
}
|
|
105
|
-
this._onSettledCallbacks.forEach((cb) => cb(success ? res : error));
|
|
106
102
|
const wait = this.getWait();
|
|
107
103
|
if (wait > 0) {
|
|
108
104
|
setTimeout(() => this.tick(), wait);
|
|
@@ -117,6 +113,7 @@ class AsyncQueuer {
|
|
|
117
113
|
* Checks for and removes expired items from the queuer
|
|
118
114
|
*/
|
|
119
115
|
checkExpiredItems() {
|
|
116
|
+
var _a, _b, _c, _d;
|
|
120
117
|
if (this._options.expirationDuration === Infinity && this._options.getIsExpired === defaultOptions.getIsExpired)
|
|
121
118
|
return;
|
|
122
119
|
const now = Date.now();
|
|
@@ -139,22 +136,23 @@ class AsyncQueuer {
|
|
|
139
136
|
this._items.splice(index, 1);
|
|
140
137
|
this._itemTimestamps.splice(index, 1);
|
|
141
138
|
this._expirationCount++;
|
|
142
|
-
this._options.onExpire(expiredItem, this);
|
|
139
|
+
(_b = (_a = this._options).onExpire) == null ? void 0 : _b.call(_a, expiredItem, this);
|
|
143
140
|
}
|
|
144
141
|
if (expiredIndices.length > 0) {
|
|
145
|
-
this._options.onItemsChange(this);
|
|
142
|
+
(_d = (_c = this._options).onItemsChange) == null ? void 0 : _d.call(_c, this);
|
|
146
143
|
}
|
|
147
144
|
}
|
|
148
145
|
/**
|
|
149
146
|
* Starts the queuer and processes items
|
|
150
147
|
*/
|
|
151
148
|
start() {
|
|
149
|
+
var _a, _b;
|
|
152
150
|
this._running = true;
|
|
153
151
|
if (!this._pendingTick && !this.getIsEmpty()) {
|
|
154
152
|
this._pendingTick = true;
|
|
155
153
|
this.tick();
|
|
156
154
|
}
|
|
157
|
-
this._options.onIsRunningChange(this);
|
|
155
|
+
(_b = (_a = this._options).onIsRunningChange) == null ? void 0 : _b.call(_a, this);
|
|
158
156
|
return new Promise((resolve) => {
|
|
159
157
|
const checkIdle = () => {
|
|
160
158
|
if (this.getIsIdle()) {
|
|
@@ -170,23 +168,27 @@ class AsyncQueuer {
|
|
|
170
168
|
* Stops the queuer from processing items
|
|
171
169
|
*/
|
|
172
170
|
stop() {
|
|
171
|
+
var _a, _b;
|
|
173
172
|
this._running = false;
|
|
174
173
|
this._pendingTick = false;
|
|
175
|
-
this._options.onIsRunningChange(this);
|
|
174
|
+
(_b = (_a = this._options).onIsRunningChange) == null ? void 0 : _b.call(_a, this);
|
|
176
175
|
}
|
|
177
176
|
/**
|
|
178
177
|
* Removes all items from the queuer
|
|
179
178
|
*/
|
|
180
179
|
clear() {
|
|
180
|
+
var _a, _b;
|
|
181
181
|
this._items = [];
|
|
182
|
-
this._options.onItemsChange(this);
|
|
182
|
+
(_b = (_a = this._options).onItemsChange) == null ? void 0 : _b.call(_a, this);
|
|
183
183
|
}
|
|
184
184
|
/**
|
|
185
185
|
* Resets the queuer to its initial state
|
|
186
186
|
*/
|
|
187
187
|
reset(withInitialItems) {
|
|
188
188
|
this.clear();
|
|
189
|
-
this.
|
|
189
|
+
this._successCount = 0;
|
|
190
|
+
this._errorCount = 0;
|
|
191
|
+
this._settledCount = 0;
|
|
190
192
|
if (withInitialItems) {
|
|
191
193
|
this._items = [...this._options.initialItems];
|
|
192
194
|
}
|
|
@@ -196,60 +198,47 @@ class AsyncQueuer {
|
|
|
196
198
|
* Adds a task to the queuer
|
|
197
199
|
*/
|
|
198
200
|
addItem(fn, position = this._options.addItemsTo, runOnItemsChange = true) {
|
|
201
|
+
var _a, _b, _c, _d;
|
|
199
202
|
if (this.getIsFull()) {
|
|
200
203
|
this._rejectionCount++;
|
|
201
|
-
this._options.onReject(fn, this);
|
|
202
|
-
return
|
|
204
|
+
(_b = (_a = this._options).onReject) == null ? void 0 : _b.call(_a, fn, this);
|
|
205
|
+
return;
|
|
203
206
|
}
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
throw error;
|
|
214
|
-
}
|
|
215
|
-
},
|
|
216
|
-
{ priority: fn.priority ?? void 0 }
|
|
217
|
-
);
|
|
218
|
-
const priority = this._options.getPriority !== defaultOptions.getPriority ? this._options.getPriority(task) : task.priority;
|
|
219
|
-
if (priority !== void 0) {
|
|
220
|
-
const insertIndex = this._items.findIndex((existing) => {
|
|
221
|
-
const existingPriority = this._options.getPriority !== defaultOptions.getPriority ? this._options.getPriority(existing) : existing.priority;
|
|
222
|
-
return existingPriority > priority;
|
|
223
|
-
});
|
|
224
|
-
if (insertIndex === -1) {
|
|
225
|
-
this._items.push(task);
|
|
226
|
-
this._itemTimestamps.push(Date.now());
|
|
227
|
-
} else {
|
|
228
|
-
this._items.splice(insertIndex, 0, task);
|
|
229
|
-
this._itemTimestamps.splice(insertIndex, 0, Date.now());
|
|
230
|
-
}
|
|
207
|
+
const priority = this._options.getPriority !== defaultOptions.getPriority ? this._options.getPriority(fn) : fn.priority;
|
|
208
|
+
if (priority !== void 0) {
|
|
209
|
+
const insertIndex = this._items.findIndex((existing) => {
|
|
210
|
+
const existingPriority = this._options.getPriority !== defaultOptions.getPriority ? this._options.getPriority(existing) : existing.priority;
|
|
211
|
+
return existingPriority > priority;
|
|
212
|
+
});
|
|
213
|
+
if (insertIndex === -1) {
|
|
214
|
+
this._items.push(fn);
|
|
215
|
+
this._itemTimestamps.push(Date.now());
|
|
231
216
|
} else {
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
this._itemTimestamps.unshift(Date.now());
|
|
235
|
-
} else {
|
|
236
|
-
this._items.push(task);
|
|
237
|
-
this._itemTimestamps.push(Date.now());
|
|
238
|
-
}
|
|
239
|
-
}
|
|
240
|
-
if (runOnItemsChange) {
|
|
241
|
-
this._options.onItemsChange(this);
|
|
217
|
+
this._items.splice(insertIndex, 0, fn);
|
|
218
|
+
this._itemTimestamps.splice(insertIndex, 0, Date.now());
|
|
242
219
|
}
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
this.
|
|
220
|
+
} else {
|
|
221
|
+
if (position === "front") {
|
|
222
|
+
this._items.unshift(fn);
|
|
223
|
+
this._itemTimestamps.unshift(Date.now());
|
|
224
|
+
} else {
|
|
225
|
+
this._items.push(fn);
|
|
226
|
+
this._itemTimestamps.push(Date.now());
|
|
246
227
|
}
|
|
247
|
-
}
|
|
228
|
+
}
|
|
229
|
+
if (runOnItemsChange) {
|
|
230
|
+
(_d = (_c = this._options).onItemsChange) == null ? void 0 : _d.call(_c, this);
|
|
231
|
+
}
|
|
232
|
+
if (this._running && !this._pendingTick) {
|
|
233
|
+
this._pendingTick = true;
|
|
234
|
+
this.tick();
|
|
235
|
+
}
|
|
248
236
|
}
|
|
249
237
|
/**
|
|
250
238
|
* Removes and returns an item from the queuer
|
|
251
239
|
*/
|
|
252
240
|
getNextItem(position = this._options.getItemsFrom) {
|
|
241
|
+
var _a, _b, _c, _d;
|
|
253
242
|
let item;
|
|
254
243
|
if (position === "front") {
|
|
255
244
|
item = this._items.shift();
|
|
@@ -259,9 +248,8 @@ class AsyncQueuer {
|
|
|
259
248
|
this._itemTimestamps.pop();
|
|
260
249
|
}
|
|
261
250
|
if (item !== void 0) {
|
|
262
|
-
this.
|
|
263
|
-
this._options.
|
|
264
|
-
this._options.onGetNextItem(item, this);
|
|
251
|
+
(_b = (_a = this._options).onItemsChange) == null ? void 0 : _b.call(_a, this);
|
|
252
|
+
(_d = (_c = this._options).onGetNextItem) == null ? void 0 : _d.call(_c, item, this);
|
|
265
253
|
}
|
|
266
254
|
return item;
|
|
267
255
|
}
|
|
@@ -311,10 +299,22 @@ class AsyncQueuer {
|
|
|
311
299
|
return [...this._items];
|
|
312
300
|
}
|
|
313
301
|
/**
|
|
314
|
-
* Returns the number of items that have been
|
|
302
|
+
* Returns the number of items that have been successfully processed
|
|
303
|
+
*/
|
|
304
|
+
getSuccessCount() {
|
|
305
|
+
return this._successCount;
|
|
306
|
+
}
|
|
307
|
+
/**
|
|
308
|
+
* Returns the number of items that have failed processing
|
|
315
309
|
*/
|
|
316
|
-
|
|
317
|
-
return this.
|
|
310
|
+
getErrorCount() {
|
|
311
|
+
return this._errorCount;
|
|
312
|
+
}
|
|
313
|
+
/**
|
|
314
|
+
* Returns the number of items that have completed processing (success or error)
|
|
315
|
+
*/
|
|
316
|
+
getSettledCount() {
|
|
317
|
+
return this._settledCount;
|
|
318
318
|
}
|
|
319
319
|
/**
|
|
320
320
|
* Returns the number of items that have been rejected from the queuer
|
|
@@ -334,37 +334,6 @@ class AsyncQueuer {
|
|
|
334
334
|
getIsIdle() {
|
|
335
335
|
return this._running && this.getIsEmpty() && this._activeItems.size === 0;
|
|
336
336
|
}
|
|
337
|
-
/**
|
|
338
|
-
* Adds a callback to be called when a task succeeds
|
|
339
|
-
*/
|
|
340
|
-
onSuccess(cb) {
|
|
341
|
-
this._onSuccessCallbacks.push(cb);
|
|
342
|
-
return () => {
|
|
343
|
-
this._onSuccessCallbacks = this._onSuccessCallbacks.filter(
|
|
344
|
-
(d) => d !== cb
|
|
345
|
-
);
|
|
346
|
-
};
|
|
347
|
-
}
|
|
348
|
-
/**
|
|
349
|
-
* Adds a callback to be called when a task errors
|
|
350
|
-
*/
|
|
351
|
-
onError(cb) {
|
|
352
|
-
this._onErrorCallbacks.push(cb);
|
|
353
|
-
return () => {
|
|
354
|
-
this._onErrorCallbacks = this._onErrorCallbacks.filter((d) => d !== cb);
|
|
355
|
-
};
|
|
356
|
-
}
|
|
357
|
-
/**
|
|
358
|
-
* Adds a callback to be called when a task is settled
|
|
359
|
-
*/
|
|
360
|
-
onSettled(cb) {
|
|
361
|
-
this._onSettledCallbacks.push(cb);
|
|
362
|
-
return () => {
|
|
363
|
-
this._onSettledCallbacks = this._onSettledCallbacks.filter(
|
|
364
|
-
(d) => d !== cb
|
|
365
|
-
);
|
|
366
|
-
};
|
|
367
|
-
}
|
|
368
337
|
/**
|
|
369
338
|
* Returns the number of items that have expired from the queuer
|
|
370
339
|
*/
|