function asyncRateLimit<TFn>(fn, initialOptions): (...args) => Promise<undefined | ReturnType<TFn>>
function asyncRateLimit<TFn>(fn, initialOptions): (...args) => Promise<undefined | ReturnType<TFn>>
定义于: async-rate-limiter.ts:539
创建一个异步限速函数,该函数在一个时间窗口内最多执行给定函数指定的次数。
与非异步限速器不同,此异步版本支持从限速函数返回结果,使其成为 API 调用和其他异步操作的理想选择,因为您想要的是 maybeExecute 调用的结果,而不是在限速函数内部将结果设置到状态变量中。
速率限制器支持两种类型的窗口
请注意,限速是一种比节流或防抖更简单的执行控制形式。
状态管理
如果您需要更智能的执行控制,请考虑使用 throttle() 或 debounce()。当您确实需要强制执行在特定时间段内的执行次数硬限制时,请使用限速。
错误处理
• TFn extends AnyAsyncFunction
TFn
Function
尝试在配置的限制内执行速率限制函数。如果当前窗口中的调用次数超过限制,则会拒绝执行。
错误处理
...Parameters<TFn>
Promise<undefined | ReturnType<TFn>>
一个 Promise,它会解析为函数的返回值,如果错误被 onError 处理,则返回 undefined
如果未配置 onError 处理程序,则限速函数中的错误。
const rateLimiter = new AsyncRateLimiter(fn, { limit: 5, window: 1000 });
// First 5 calls will return a promise that resolves with the result
const result = await rateLimiter.maybeExecute('arg1', 'arg2');
// Additional calls within the window will return undefined
const result2 = await rateLimiter.maybeExecute('arg1', 'arg2'); // undefined
const rateLimiter = new AsyncRateLimiter(fn, { limit: 5, window: 1000 });
// First 5 calls will return a promise that resolves with the result
const result = await rateLimiter.maybeExecute('arg1', 'arg2');
// Additional calls within the window will return undefined
const result2 = await rateLimiter.maybeExecute('arg1', 'arg2'); // undefined
// 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
您的每周 JavaScript 资讯。每周一免费发送给超过 10 万开发者。