function asyncRateLimit<TFn>(fn, initialOptions): (...args) => Promise<undefined | ReturnType<TFn>>
function asyncRateLimit<TFn>(fn, initialOptions): (...args) => Promise<undefined | ReturnType<TFn>>
Defined in: async-rate-limiter.ts:408
Creates an async rate-limited function that will execute the provided function up to a maximum number of times within a time window.
Unlike the non-async rate limiter, this async version supports returning values from the rate-limited function, making it ideal for API calls and other async operations where you want the result of the maybeExecute call instead of setting the result on a state variable from within the rate-limited function.
The rate limiter supports two types of windows:
Note that rate limiting is a simpler form of execution control compared to throttling or debouncing:
Consider using throttle() or debounce() if you need more intelligent execution control. Use rate limiting when you specifically need to enforce a hard limit on the number of executions within a time period.
Error Handling:
• TFn extends AnyAsyncFunction
TFn
Function
Attempts to execute the rate-limited function if within the configured limits. Will reject execution if the number of calls in the current window exceeds the limit. If execution is allowed, waits for any previous execution to complete before proceeding.
Error Handling:
...Parameters<TFn>
Promise<undefined | ReturnType<TFn>>
A promise that resolves with the function's return value, or undefined if an error occurred and was handled by onError
The error from the rate-limited function if no onError handler is configured
const rateLimiter = new AsyncRateLimiter(fn, { limit: 5, window: 1000 });
// First 5 calls will execute
await rateLimiter.maybeExecute('arg1', 'arg2');
// Additional calls within the window will be rejected
await rateLimiter.maybeExecute('arg1', 'arg2'); // Rejected
const rateLimiter = new AsyncRateLimiter(fn, { limit: 5, window: 1000 });
// First 5 calls will execute
await rateLimiter.maybeExecute('arg1', 'arg2');
// Additional calls within the window will be rejected
await rateLimiter.maybeExecute('arg1', 'arg2'); // Rejected
// Rate limit to 5 calls per minute with a sliding window
const rateLimited = asyncRateLimit(makeApiCall, {
limit: 5,
window: 60000,
windowType: 'sliding',
onError: (error) => {
console.error('API call failed:', error);
},
onReject: (rateLimiter) => {
console.log(`Rate limit exceeded. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);
}
});
// First 5 calls will execute immediately
// Additional calls will be rejected until the minute window resets
// Returns the API response directly
const result = await rateLimited();
// For more even execution, consider using throttle instead:
const throttled = throttle(makeApiCall, { wait: 12000 }); // One call every 12 seconds
// Rate limit to 5 calls per minute with a sliding window
const rateLimited = asyncRateLimit(makeApiCall, {
limit: 5,
window: 60000,
windowType: 'sliding',
onError: (error) => {
console.error('API call failed:', error);
},
onReject: (rateLimiter) => {
console.log(`Rate limit exceeded. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);
}
});
// First 5 calls will execute immediately
// Additional calls will be rejected until the minute window resets
// Returns the API response directly
const result = await rateLimited();
// For more even execution, consider using throttle instead:
const throttled = throttle(makeApiCall, { wait: 12000 }); // One call every 12 seconds
Your weekly dose of JavaScript news. Delivered every Monday to over 100,000 devs, for free.