框架
版本
防抖器 API 参考
节流器 API 参考
速率限制器 API 参考
队列 API 参考
批处理器 API 参考

异步节流

函数: asyncThrottle()

ts
function asyncThrottle<TFn>(fn, initialOptions): (...args) => Promise<undefined | ReturnType<TFn>>
function asyncThrottle<TFn>(fn, initialOptions): (...args) => Promise<undefined | ReturnType<TFn>>

定义于: async-throttler.ts:500

创建一个异步节流函数,该函数限制函数的执行频率。节流函数将在一周期内最多执行一次,即使被多次调用。如果在执行期间被调用,它将等待直到执行完成,然后才安排下一次调用。

与非异步节流器不同,此异步版本支持从节流函数返回结果,这使其成为 API 调用和其他异步操作的理想选择,在这些操作中,您希望获取 maybeExecute 调用的结果,而不是在节流函数内部将结果设置到状态变量中。

错误处理

  • 如果提供了 onError 处理程序,它将与错误和节流器实例一起被调用
  • 如果 throwOnError 为 true(当没有提供 onError 处理程序时的默认值),错误将被抛出
  • 如果 throwOnError 为 false(当提供 onError 处理程序时的默认值),错误将被吞没
  • onError 和 throwOnError 可以一起使用 - 在任何错误被抛出之前,处理程序都会被调用
  • 错误状态可以通过底层 AsyncThrottler 实例进行检查

状态管理

  • 使用 TanStack Store 进行响应式状态管理
  • 使用 initialState 在创建异步节流器时提供初始状态值
  • 使用 onSuccess 回调函数来响应成功的函数执行并实现自定义逻辑
  • 使用 onError 回调函数来响应函数执行错误并实现自定义错误处理
  • 使用 onSettled 回调函数来响应函数执行完成(成功或失败)并实现自定义逻辑
  • 状态包括错误计数、执行状态、上次执行时间和成功/完成计数
  • 可以通过底层 AsyncThrottler 实例的 store.state 属性访问状态
  • 在使用框架适配器(React/Solid)时,状态从 hook 的 state 属性访问

类型参数

TFn extends AnyAsyncFunction

参数

fn

TFn

initialOptions

AsyncThrottlerOptions<TFn>

Returns (返回)

Function

尝试执行节流函数。执行行为取决于节流器选项

  • 如果自上次执行以来已经过去了足够的时间(>=等待周期)

    • 当 leading=true 时:立即执行
    • 当 leading=false 时:等待下一次尾部执行
  • 在等待周期内

    • 当 trailing=true 时:安排在等待周期结束时执行
    • 当 trailing=false 时:丢弃执行

参数

args

...Parameters<TFn>

Returns (返回)

Promise<undefined | ReturnType<TFn>>

示例

ts
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');

示例

ts
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);
我们的合作伙伴
Code Rabbit
Unkey
订阅 Bytes

您的每周 JavaScript 资讯。每周一免费发送给超过 10 万开发者。

Bytes

无垃圾邮件。您可以随时取消订阅。

订阅 Bytes

您的每周 JavaScript 资讯。每周一免费发送给超过 10 万开发者。

Bytes

无垃圾邮件。您可以随时取消订阅。