function asyncThrottle<TFn>(fn, initialOptions): (...args) => Promise<undefined | ReturnType<TFn>>
function asyncThrottle<TFn>(fn, initialOptions): (...args) => Promise<undefined | ReturnType<TFn>>
创建一个异步节流函数,该函数限制函数的执行频率。节流函数将在一周期内最多执行一次,即使被多次调用。如果在执行期间被调用,它将等待直到执行完成,然后才安排下一次调用。
与非异步节流器不同,此异步版本支持从节流函数返回结果,这使其成为 API 调用和其他异步操作的理想选择,在这些操作中,您希望获取 maybeExecute 调用的结果,而不是在节流函数内部将结果设置到状态变量中。
错误处理
状态管理
• TFn extends AnyAsyncFunction
TFn
Function
尝试执行节流函数。执行行为取决于节流器选项
如果自上次执行以来已经过去了足够的时间(>=等待周期)
在等待周期内
...Parameters<TFn>
Promise<undefined | ReturnType<TFn>>
const throttled = new AsyncThrottler(fn, { wait: 1000 });
// First call executes immediately
await throttled.maybeExecute('a', 'b');
// Call during wait period - gets throttled
await throttled.maybeExecute('c', 'd');
const throttled = new AsyncThrottler(fn, { wait: 1000 });
// First call executes immediately
await throttled.maybeExecute('a', 'b');
// Call during wait period - gets throttled
await throttled.maybeExecute('c', 'd');
const throttled = asyncThrottle(async (value: string) => {
const result = await saveToAPI(value);
return result; // Return value is preserved
}, {
wait: 1000,
onError: (error) => {
console.error('API call failed:', error);
}
});
// This will execute at most once per second
// Returns the API response directly
const result = await throttled(inputElement.value);
const throttled = asyncThrottle(async (value: string) => {
const result = await saveToAPI(value);
return result; // Return value is preserved
}, {
wait: 1000,
onError: (error) => {
console.error('API call failed:', error);
}
});
// This will execute at most once per second
// Returns the API response directly
const result = await throttled(inputElement.value);
您的每周 JavaScript 资讯。每周一免费发送给超过 10 万开发者。