util: implement util.throttle

Often closely related to util.debounce use cases, this adds an
implementation of throttle(fn) .. returns a function that limits
the number of concurrent invocations of fn.

Signed-off-by: James M Snell <jasnell@gmail.com>
Assisted-by: Opencode
PR-URL: https://github.com/nodejs/node/pull/65899
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
This commit is contained in:
James M Snell authored and Antoine du Hamel committed 2026-09-17 17:24:34 +02:00
1 parent 336f33ccc1
commit 3ce4d23bbb
6 files changed
+940

No files matched your search

+7
View File
@@ -3218,6 +3218,13 @@ This error represents a failed test. Additional information about the failure
is available via the `cause` property. The `failureType` property specifies
what the test was doing when the failure occurred.
<a id="ERR_THROTTLED"></a>
### `ERR_THROTTLED`
A call was dropped because a throttled function could not invoke it immediately
or its pending queue was full.
<a id="ERR_TLS_ALPN_CALLBACK_INVALID_RESULT"></a>
### `ERR_TLS_ALPN_CALLBACK_INVALID_RESULT`
+109
View File
@@ -485,6 +485,115 @@ process.stdin.on('data', (data) => {
onInactivity();
```
## `util.throttle(fn, limit, interval[, options])`
<!-- YAML
added: REPLACEME
-->
* `fn` {Function} The function to throttle.
* `limit` {integer} The maximum number of times to invoke `fn` during an
interval. Must be greater than `0`.
* `interval` {integer} The length of each interval in milliseconds.
* `options` {Object}
* `concurrency` {number} The maximum number of invocations of `fn` whose
return values may be unsettled at once. Must be a positive integer or
`Infinity`. **Default:** `Infinity`.
* `maxPending` {number} The maximum number of calls that may be queued when
`overflow` is `'queue'`. Must be a non-negative integer or `Infinity`.
**Default:** `Infinity`.
* `overflow` {string} Determines how calls exceeding the limit are handled.
**Default:** `'queue'`.
* `'queue'`: Queue calls in the order received.
* `'drop'`: Reject calls immediately without queueing them.
* `signal` {AbortSignal} An `AbortSignal` that cancels pending calls and
prevents future calls when aborted.
* `strict` {boolean} When `true`, ensures that `limit` is not exceeded during
any rolling interval. **Default:** `false`.
* Returns: {Function} The throttled function.
Creates a function that limits how often `fn` is invoked. By default, calls that
exceed the limit are queued in the order received rather than discarded. The
throttled function returns a {Promise} for the value returned by `fn`. If `fn`
throws or returns a rejected promise, the returned promise is rejected with the
same reason.
An invocation starts only when both rate and concurrency capacity are
available. Rate capacity is consumed when `fn` starts, not when a call enters
the queue. Concurrency capacity is released when the value returned by `fn`
settles. Non-promise values settle during the next microtask.
When `options.overflow` is `'drop'`, calls made without available rate or
concurrency capacity are rejected immediately. When `options.overflow` is
`'queue'` and `options.maxPending` calls are already queued, additional calls
are also rejected immediately. `maxPending` has no effect when `overflow` is
`'drop'`.
In both cases, rejected calls return a promise rejected with an
`ERR_THROTTLED` error. The rejected promise is marked as handled, so ignoring it
does not emit an `'unhandledRejection'` event. Awaiting or explicitly handling
the promise still observes the rejection. Rejected calls do not consume rate
or concurrency capacity, enter the queue, or schedule a timeout.
By default, the interval begins when the first call in a new window invokes
`fn`. Up to `limit` calls can invoke `fn` during that window. Queued calls are
processed in groups of up to `limit` as each subsequent window begins. This
windowed behavior can result in calls occurring close together at a window
boundary.
When `options.strict` is `true`, invocation times are tracked individually.
This ensures that no more than `limit` calls begin during any rolling interval,
at the cost of additional bookkeeping.
If `options.signal` is aborted, pending and future calls reject with an
`AbortError`, with the signal's reason set as the error's `cause`, and `fn` is
not invoked by those calls. If the signal is already aborted, `throttle()`
throws an `AbortError`.
The returned function has the following properties:
* `cancel([reason])` cancels all queued calls and resets the current throttle
window. The queued promises reject with an `AbortError`. If provided,
`reason` is set as the error's `cause`. Does not cancel invocations that have
already started.
* `hasImmediateCapacity()` returns `true` if a call made at that moment could
invoke `fn` without being queued or rejected. The check does not reserve
capacity, and the throttled function always checks again when called. It
returns `false` while calls are queued to preserve their order. Callers can
avoid creating a timeout by only calling the throttled function when this
method returns `true`.
* `pending` {Promise|null} is the promise returned by the most recently queued
call, or `null` if no invocation is queued.
* `pendingCount` {integer} is the number of calls awaiting invocation.
* `activeCount` {integer} is the number of invocations whose return values have
not settled.
* `ref()` makes the pending and future timeout keep the Node.js event loop
active. Returns the throttled function.
* `unref()` allows the event loop to exit while a timeout is pending. This also
applies to future timeouts. Returns the throttled function.
Calls that have already invoked `fn` are not affected by `cancel()` or by an
aborted signal. When invoked, `fn` has the throttled function as its `this`
value. The throttled function preserves the `name` and `length` of `fn`.
```mjs
import { throttle } from 'node:util';
const request = throttle(async (id) => {
const response = await fetch(`https://example.com/items/${id}`);
return response.json();
}, 2, 1_000);
// At most two requests begin during each one-second interval. All other calls
// remain queued and retain their original arguments.
const results = await Promise.all([
request(1),
request(2),
request(3),
request(4),
]);
```
## `util.diff(actual, expected)`
<!-- YAML
+1
View File
@@ -1863,6 +1863,7 @@ E('ERR_TEST_FAILURE', function(error, failureType) {
this.cause = error;
return msg;
}, Error);
E('ERR_THROTTLED', 'The call was dropped by the throttled function', Error);
E('ERR_TLS_ALPN_CALLBACK_INVALID_RESULT', (value, protocols) => {
return `ALPN callback returned a value (${
value
+370
View File
@@ -0,0 +1,370 @@
'use strict';
const {
ArrayPrototypePush,
ArrayPrototypeSlice,
ObjectDefineProperties,
PromisePrototypeThen,
PromiseReject,
PromiseResolve,
PromiseWithResolvers,
ReflectApply,
} = primordials;
const {
AbortError,
codes: {
ERR_THROTTLED,
},
} = require('internal/errors');
const {
validateAbortSignal,
validateBoolean,
validateFunction,
validateInteger,
validateObject,
validateOneOf,
} = require('internal/validators');
const { addAbortListener } = require('internal/events/abort_listener');
const { kEmptyObject } = require('internal/util');
const { TIMEOUT_MAX } = require('internal/timers');
const { clearTimeout, setTimeout } = require('timers');
const timersBinding = internalBinding('timers');
const { markPromiseAsHandled } = internalBinding('util');
/**
* @typedef {object} ThrottleOptions
* @property {number} [concurrency] The maximum number of unsettled invocations.
* @property {number} [maxPending] The maximum number of queued calls.
* @property {'queue'|'drop'} [overflow] How calls exceeding the limit are handled.
* @property {AbortSignal} [signal] An AbortSignal that cancels pending and future calls.
* @property {boolean} [strict] Whether to enforce the limit over a rolling interval.
*/
/**
* Creates a function that invokes `fn` at most `limit` times per `interval`.
* @param {Function} fn
* @param {number} limit
* @param {number} interval
* @param {ThrottleOptions} [options]
* @returns {Function}
*/
function throttle(fn, limit, interval, options = kEmptyObject) {
validateFunction(fn, 'fn');
validateInteger(limit, 'limit', 1);
validateInteger(interval, 'interval', 0, TIMEOUT_MAX);
validateObject(options, 'options');
const {
concurrency = Infinity,
maxPending = Infinity,
overflow = 'queue',
signal,
strict = false,
} = options;
if (concurrency !== Infinity) {
validateInteger(concurrency, 'options.concurrency', 1);
}
if (maxPending !== Infinity) {
validateInteger(maxPending, 'options.maxPending', 0);
}
validateOneOf(overflow, 'options.overflow', ['queue', 'drop']);
validateAbortSignal(signal, 'options.signal');
validateBoolean(strict, 'options.strict');
if (signal?.aborted) {
throw new AbortError(undefined, { __proto__: null, cause: signal.reason });
}
let abortError;
let activeCount = 0;
let pendingCalls = [];
let pendingIndex = 0;
let refed = true;
let strictIndex = 0;
let strictTicks = [];
let timeout;
let windowCount = 0;
let windowStart;
function pendingCount() {
return pendingCalls.length - pendingIndex;
}
function dequeue() {
const call = pendingCalls[pendingIndex];
pendingCalls[pendingIndex++] = undefined;
if (pendingIndex === pendingCalls.length) {
pendingCalls = [];
pendingIndex = 0;
} else if (pendingIndex > 1024 && pendingIndex * 2 >= pendingCalls.length) {
pendingCalls = ArrayPrototypeSlice(pendingCalls, pendingIndex);
pendingIndex = 0;
}
return call;
}
function rejectPending(error) {
const calls = pendingCalls;
const start = pendingIndex;
pendingCalls = [];
pendingIndex = 0;
for (let i = start; i < calls.length; i++) {
calls[i].reject(error);
}
}
function resetLimiter() {
strictIndex = 0;
strictTicks = [];
windowCount = 0;
windowStart = undefined;
}
function cancelWithError(error) {
if (timeout !== undefined) {
clearTimeout(timeout);
timeout = undefined;
}
resetLimiter();
rejectPending(error);
}
function cancel(reason) {
const error = reason === undefined ?
new AbortError() :
new AbortError(undefined, { __proto__: null, cause: reason });
cancelWithError(error);
}
function abort() {
if (abortError === undefined) {
abortError = signal.reason === undefined ?
new AbortError() :
new AbortError(undefined, { __proto__: null, cause: signal.reason });
}
cancelWithError(abortError);
}
function ref() {
refed = true;
timeout?.ref();
return throttled;
}
function unref() {
refed = false;
timeout?.unref();
return throttled;
}
function hasImmediateCapacity() {
if (signal?.aborted ||
pendingCount() !== 0 ||
activeCount >= concurrency) {
return false;
}
const now = timersBinding.getLibuvNow();
if (strict) {
let index = strictIndex;
while (index < strictTicks.length &&
now - strictTicks[index] >= interval) {
index++;
}
return strictTicks.length - index < limit;
}
return windowStart === undefined ||
now - windowStart >= interval ||
windowCount < limit;
}
function pruneStrictTicks(now) {
while (strictIndex < strictTicks.length &&
now - strictTicks[strictIndex] >= interval) {
strictIndex++;
}
if (strictIndex === strictTicks.length) {
strictIndex = 0;
strictTicks = [];
} else if (strictIndex > 1024 && strictIndex * 2 >= strictTicks.length) {
strictTicks = ArrayPrototypeSlice(strictTicks, strictIndex);
strictIndex = 0;
}
}
function hasCapacity(now) {
if (strict) {
pruneStrictTicks(now);
return strictTicks.length - strictIndex < limit;
}
if (windowStart === undefined || now - windowStart >= interval) {
windowCount = 0;
windowStart = now;
}
return windowCount < limit;
}
function reserve(now) {
if (strict) {
ArrayPrototypePush(strictTicks, now);
} else {
windowCount++;
}
}
function onSettled() {
activeCount--;
drain();
}
function invoke(call) {
activeCount++;
let resultPromise;
try {
resultPromise = PromiseResolve(ReflectApply(fn, throttled, call.args));
} catch (error) {
resultPromise = PromiseReject(error);
}
call.resolve(resultPromise);
PromisePrototypeThen(resultPromise, onSettled, onSettled);
}
function drop() {
const promise = PromiseReject(new ERR_THROTTLED());
markPromiseAsHandled(promise);
return promise;
}
function schedule() {
if (timeout !== undefined ||
pendingCount() === 0 ||
activeCount >= concurrency) {
return;
}
const now = timersBinding.getLibuvNow();
if (hasCapacity(now)) {
drain();
return;
}
const delay = strict ?
strictTicks[strictIndex] + interval - now :
windowStart + interval - now;
timeout = setTimeout(onTimeout, delay);
if (!refed) timeout.unref();
}
function drain() {
if (signal?.aborted) {
abort();
return;
}
while (pendingCount() !== 0 && activeCount < concurrency) {
const now = timersBinding.getLibuvNow();
if (!hasCapacity(now)) break;
const call = dequeue();
reserve(now);
invoke(call);
}
schedule();
}
function onTimeout() {
timeout = undefined;
drain();
}
function throttled(...callArgs) {
if (signal?.aborted) abort();
if (abortError !== undefined) return PromiseReject(abortError);
const now = timersBinding.getLibuvNow();
const canInvoke = pendingCount() === 0 &&
activeCount < concurrency &&
hasCapacity(now);
if (!canInvoke &&
(overflow === 'drop' || pendingCount() >= maxPending)) {
return drop();
}
const call = PromiseWithResolvers();
call.args = callArgs;
if (canInvoke) {
reserve(now);
invoke(call);
} else {
ArrayPrototypePush(pendingCalls, call);
schedule();
}
return call.promise;
}
function createFn(value) {
return {
__proto__: null,
configurable: true,
enumerable: true,
writable: true,
value,
};
}
ObjectDefineProperties(throttled, {
__proto__: null,
cancel: createFn(cancel),
hasImmediateCapacity: createFn(hasImmediateCapacity),
ref: createFn(ref),
unref: createFn(unref),
pending: {
__proto__: null,
enumerable: false,
get() {
return pendingCount() === 0 ? null :
pendingCalls[pendingCalls.length - 1].promise;
},
},
pendingCount: {
__proto__: null,
enumerable: false,
get: pendingCount,
},
activeCount: {
__proto__: null,
enumerable: false,
get() {
return activeCount;
},
},
length: {
__proto__: null,
configurable: true,
value: fn.length,
},
name: {
__proto__: null,
configurable: true,
value: fn.name,
},
});
if (signal !== undefined) {
addAbortListener(signal, abort);
}
return throttled;
}
module.exports = throttle;
+6
View File
@@ -675,6 +675,12 @@ ObjectDefineProperties(module.exports, {
enumerable: true,
get() { return require('internal/util/debounce'); },
},
throttle: {
__proto__: null,
configurable: true,
enumerable: true,
get() { return require('internal/util/throttle'); },
},
});
defineLazyProperties(
+447
View File
@@ -0,0 +1,447 @@
// Flags: --expose-internals
'use strict';
const common = require('../common');
const assert = require('node:assert');
const { createHook } = require('node:async_hooks');
const { setImmediate, setTimeout } = require('node:timers/promises');
const { throttle } = require('node:util');
const { TIMEOUT_MAX } = require('internal/timers');
process.on('unhandledRejection', common.mustNotCall());
for (const value of [undefined, null, true, 0, 'fn', {}, [], Symbol()]) {
assert.throws(() => throttle(value, 1, 1), {
code: 'ERR_INVALID_ARG_TYPE',
});
}
for (const value of [undefined, null, true, '1', {}, [], Symbol()]) {
assert.throws(() => throttle(() => {}, value, 1), {
code: 'ERR_INVALID_ARG_TYPE',
});
}
for (const value of [-1, 0, 0.5, NaN, Infinity]) {
assert.throws(() => throttle(() => {}, value, 1), {
code: 'ERR_OUT_OF_RANGE',
});
}
for (const value of [undefined, null, true, '1', {}, [], Symbol()]) {
assert.throws(() => throttle(() => {}, 1, value), {
code: 'ERR_INVALID_ARG_TYPE',
});
}
for (const value of [-1, 0.5, NaN, Infinity, TIMEOUT_MAX + 1]) {
assert.throws(() => throttle(() => {}, 1, value), {
code: 'ERR_OUT_OF_RANGE',
});
}
for (const value of [null, true, 1, 'options', []]) {
assert.throws(() => throttle(() => {}, 1, 1, value), {
code: 'ERR_INVALID_ARG_TYPE',
});
}
assert.throws(() => throttle(() => {}, 1, 1, { signal: {} }), {
code: 'ERR_INVALID_ARG_TYPE',
});
assert.throws(() => throttle(() => {}, 1, 1, { strict: 1 }), {
code: 'ERR_INVALID_ARG_TYPE',
});
for (const value of [null, true, 0, 'invalid', {}, []]) {
assert.throws(() => throttle(() => {}, 1, 1, { overflow: value }), {
code: 'ERR_INVALID_ARG_VALUE',
});
}
for (const option of ['concurrency', 'maxPending']) {
for (const value of [null, true, '1', {}, [], Symbol()]) {
assert.throws(() => throttle(() => {}, 1, 1, { [option]: value }), {
code: 'ERR_INVALID_ARG_TYPE',
});
}
}
for (const value of [-1, 0, 0.5, NaN, -Infinity]) {
assert.throws(() => throttle(() => {}, 1, 1, { concurrency: value }), {
code: 'ERR_OUT_OF_RANGE',
});
}
for (const value of [-1, 0.5, NaN, -Infinity]) {
assert.throws(() => throttle(() => {}, 1, 1, { maxPending: value }), {
code: 'ERR_OUT_OF_RANGE',
});
}
// Explicit Infinity values are accepted.
throttle(() => {}, 1, 1, {
concurrency: Infinity,
maxPending: Infinity,
});
{
const reason = new Error('already aborted');
assert.throws(
() => throttle(() => {}, 1, 1, {
signal: AbortSignal.abort(reason),
}),
(error) => error.code === 'ABORT_ERR' && error.cause === reason,
);
}
(async () => {
{
const values = [];
const times = [];
const start = Date.now();
const throttled = throttle(common.mustCall(function(value) {
assert.strictEqual(this, throttled);
values.push(value);
times.push(Date.now() - start);
return value;
}, 5), 2, 40);
assert.strictEqual(typeof throttled.cancel, 'function');
assert.strictEqual(typeof throttled.hasImmediateCapacity, 'function');
assert.strictEqual(typeof throttled.ref, 'function');
assert.strictEqual(typeof throttled.unref, 'function');
assert.strictEqual(throttled.pending, null);
assert.strictEqual(throttled.pendingCount, 0);
assert.strictEqual(throttled.activeCount, 0);
assert.strictEqual(throttled.hasImmediateCapacity(), true);
const first = throttled(1);
const second = throttled(2);
const third = throttled(3);
const fourth = throttled(4);
const fifth = throttled(5);
assert(first instanceof Promise);
assert(second instanceof Promise);
assert.notStrictEqual(first, second);
assert.deepStrictEqual(values, [1, 2]);
assert.strictEqual(throttled.hasImmediateCapacity(), false);
assert.strictEqual(throttled.pending, fifth);
assert.strictEqual(throttled.pendingCount, 3);
assert.strictEqual(throttled.unref(), throttled);
assert.strictEqual(throttled.ref(), throttled);
assert.deepStrictEqual(
await Promise.all([first, second, third, fourth, fifth]),
[1, 2, 3, 4, 5],
);
assert.deepStrictEqual(values, [1, 2, 3, 4, 5]);
assert.strictEqual(throttled.pending, null);
assert.strictEqual(throttled.pendingCount, 0);
assert.strictEqual(throttled.activeCount, 0);
assert(times[2] - times[0] >= 30);
assert(times[4] - times[2] >= 30);
}
{
let running = 0;
let maxRunning = 0;
let timeoutCount = 0;
const releases = [];
const values = [];
const hook = createHook({
init(_asyncId, type) {
if (type === 'Timeout') timeoutCount++;
},
});
const throttled = throttle(common.mustCall((value) => {
running++;
maxRunning = Math.max(maxRunning, running);
values.push(value);
const { promise, resolve } = Promise.withResolvers();
releases.push(() => {
running--;
resolve(value);
});
return promise;
}, 4), 10, 1_000, { concurrency: 2 });
hook.enable();
const calls = [
throttled(1),
throttled(2),
throttled(3),
throttled(4),
];
hook.disable();
assert.deepStrictEqual(values, [1, 2]);
assert.strictEqual(throttled.hasImmediateCapacity(), false);
assert.strictEqual(throttled.activeCount, 2);
assert.strictEqual(throttled.pendingCount, 2);
assert.strictEqual(timeoutCount, 0);
releases[0]();
await setImmediate();
assert.deepStrictEqual(values, [1, 2, 3]);
assert.strictEqual(throttled.activeCount, 2);
assert.strictEqual(throttled.pendingCount, 1);
releases[1]();
await setImmediate();
assert.deepStrictEqual(values, [1, 2, 3, 4]);
assert.strictEqual(throttled.activeCount, 2);
assert.strictEqual(throttled.pendingCount, 0);
releases[2]();
releases[3]();
assert.deepStrictEqual(await Promise.all(calls), [1, 2, 3, 4]);
assert.strictEqual(throttled.activeCount, 0);
assert.strictEqual(maxRunning, 2);
}
{
const deferred = Promise.withResolvers();
const throttled = throttle(common.mustCall(() => deferred.promise), 10, 100, {
concurrency: 1,
overflow: 'drop',
});
const first = throttled();
const dropped = throttled();
assert.strictEqual(throttled.activeCount, 1);
assert.strictEqual(throttled.pendingCount, 0);
assert.strictEqual(throttled.hasImmediateCapacity(), false);
await setImmediate();
await assert.rejects(dropped, { code: 'ERR_THROTTLED' });
deferred.resolve('result');
assert.strictEqual(await first, 'result');
assert.strictEqual(throttled.activeCount, 0);
}
{
const values = [];
const throttled = throttle(common.mustCall((value) => {
values.push(value);
return value;
}, 2), 1, 20, { maxPending: 1 });
const first = throttled(1);
const second = throttled(2);
const dropped = throttled(3);
assert.deepStrictEqual(values, [1]);
assert.strictEqual(throttled.pendingCount, 1);
await setImmediate();
await assert.rejects(dropped, { code: 'ERR_THROTTLED' });
assert.deepStrictEqual(await Promise.all([first, second]), [1, 2]);
assert.deepStrictEqual(values, [1, 2]);
}
{
let timeoutCount = 0;
const hook = createHook({
init(_asyncId, type) {
if (type === 'Timeout') timeoutCount++;
},
});
const values = [];
const throttled = throttle(common.mustCall((value) => {
values.push(value);
return value;
}, 3), 2, 30, { overflow: 'drop' });
hook.enable();
const first = throttled(1);
const second = throttled(2);
const dropped = throttled(3);
hook.disable();
assert.deepStrictEqual(values, [1, 2]);
assert.strictEqual(timeoutCount, 0);
assert.strictEqual(throttled.pending, null);
assert.strictEqual(throttled.pendingCount, 0);
await setImmediate();
await assert.rejects(dropped, { code: 'ERR_THROTTLED' });
assert.deepStrictEqual(await Promise.all([first, second]), [1, 2]);
await setTimeout(30);
assert.strictEqual(await throttled(4), 4);
assert.deepStrictEqual(values, [1, 2, 4]);
}
{
const times = [];
const start = Date.now();
const throttled = throttle(common.mustCall((value) => {
times.push(Date.now() - start);
return value;
}, 4), 2, 80, { strict: true });
const first = throttled(1);
await setTimeout(40);
const second = throttled(2);
const third = throttled(3);
const fourth = throttled(4);
assert.deepStrictEqual(
await Promise.all([first, second, third, fourth]),
[1, 2, 3, 4],
);
assert(times[2] - times[0] >= 65);
assert(times[3] - times[1] >= 65);
assert(times[3] - times[2] >= 25);
}
{
const reason = new Error('cancelled');
const throttled = throttle(common.mustCall((value) => value, 2), 1, 100);
const first = throttled(1);
const second = throttled(2);
const third = throttled(3);
const secondRejection = assert.rejects(
second,
(error) => error.code === 'ABORT_ERR' && error.cause === reason,
);
const thirdRejection = assert.rejects(
third,
(error) => error.code === 'ABORT_ERR' && error.cause === reason,
);
throttled.cancel(reason);
assert.strictEqual(throttled.pending, null);
assert.strictEqual(throttled.pendingCount, 0);
assert.strictEqual(await first, 1);
await Promise.all([secondRejection, thirdRejection]);
// Canceling resets the limiter, so the next call can run immediately.
assert.strictEqual(await throttled(4), 4);
throttled.cancel();
}
{
const reason = new Error('stop');
const controller = new AbortController();
const throttled = throttle(common.mustCall((value) => value), 1, 100, {
signal: controller.signal,
});
const first = throttled(1);
const second = throttled(2);
const secondRejection = assert.rejects(
second,
(error) => error.code === 'ABORT_ERR' && error.cause === reason,
);
controller.abort(reason);
assert.strictEqual(throttled.hasImmediateCapacity(), false);
assert.strictEqual(await first, 1);
await secondRejection;
assert.strictEqual(throttled.pending, null);
assert.strictEqual(throttled.pendingCount, 0);
await assert.rejects(
throttled(3),
(error) => error.code === 'ABORT_ERR' && error.cause === reason,
);
}
{
const expected = new Error('failure');
const throttled = throttle(common.mustCall((value) => {
if (value === 2) throw expected;
return value;
}, 2), 1, 20);
assert.strictEqual(await throttled(1), 1);
await assert.rejects(throttled(2), (error) => error === expected);
}
{
const expected = new Error('async failure');
const throttled = throttle(common.mustCall(async () => {
throw expected;
}), 1, 0);
await assert.rejects(throttled(), (error) => error === expected);
}
{
let recursive;
const values = [];
const throttled = throttle(common.mustCall((value) => {
values.push(value);
if (value === 1) recursive = throttled(2);
return value;
}, 2), 1, 20);
const first = throttled(1);
assert.deepStrictEqual(values, [1]);
assert.strictEqual(throttled.pending, recursive);
assert.strictEqual(throttled.pendingCount, 1);
assert.deepStrictEqual(await Promise.all([first, recursive]), [1, 2]);
assert.deepStrictEqual(values, [1, 2]);
}
{
function original(first, second) {
return first + second;
}
const throttled = throttle(original, 1, 0);
assert.strictEqual(throttled.name, original.name);
assert.strictEqual(throttled.length, original.length);
assert.strictEqual(await throttled(1, 2), 3);
}
{
const values = [];
const throttled = throttle(common.mustCall((value) => {
values.push(value);
return value;
}, 5), 1, 0);
const calls = [];
for (let i = 0; i < 5; i++) calls.push(throttled(i));
assert.deepStrictEqual(values, [0, 1, 2, 3, 4]);
assert.deepStrictEqual(await Promise.all(calls), [0, 1, 2, 3, 4]);
}
{
let timeoutCount = 0;
const hook = createHook({
init(_asyncId, type) {
if (type === 'Timeout') timeoutCount++;
},
});
const throttled = throttle(common.mustCall((value) => value), 1, 100);
hook.enable();
assert.strictEqual(throttled.hasImmediateCapacity(), true);
const call = throttled(1);
assert.strictEqual(throttled.hasImmediateCapacity(), false);
if (throttled.hasImmediateCapacity()) throttled(2);
hook.disable();
assert.strictEqual(timeoutCount, 0);
assert.strictEqual(throttled.pendingCount, 0);
assert.strictEqual(await call, 1);
}
{
let timeoutCount = 0;
const hook = createHook({
init(_asyncId, type) {
if (type === 'Timeout') timeoutCount++;
},
});
const throttled = throttle(common.mustCall((value) => value), 1, 100);
hook.enable();
const first = throttled(1);
const second = throttled(2);
const third = throttled(3);
hook.disable();
const secondRejection = assert.rejects(second, { code: 'ABORT_ERR' });
const thirdRejection = assert.rejects(third, { code: 'ABORT_ERR' });
assert.strictEqual(timeoutCount, 1);
throttled.cancel();
assert.strictEqual(await first, 1);
await Promise.all([secondRejection, thirdRejection]);
}
})().then(common.mustCall());