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

异步防抖

函数:asyncDebounce()

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

定义于:async-debouncer.ts:468

创建一个异步防抖函数,它会延迟执行直到指定的等待时间过去。只有当在等待期间没有新的调用时,防抖函数才会执行一次。如果在等待期间再次调用,计时器将重置,并开始一个新的等待周期。

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

错误处理

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

状态管理

  • 使用 TanStack Store 进行响应式状态管理
  • 使用 initialState 来提供创建异步防抖函数时的初始状态值
  • 使用 onSuccess 回调函数来响应成功的函数执行并实现自定义逻辑
  • 使用 onError 回调函数来响应函数执行错误并实现自定义错误处理
  • 使用 onSettled 回调函数来响应函数执行完成(成功或失败)并实现自定义逻辑
  • 状态包括 canLeadingExecute、错误计数、执行状态以及成功/完成计数
  • 当直接使用类时,状态可以通过 asyncDebouncer.store.state 访问
  • 使用框架适配器(React/Solid)时,状态可以从 asyncDebouncer.state 访问

类型参数

TFn extends AnyAsyncFunction

参数

fn

TFn

initialOptions

AsyncDebouncerOptions<TFn>

Returns (返回)

Function

尝试执行防抖函数。如果已有调用正在进行,它将被加入队列。

错误处理

  • 如果防抖函数抛出错误且没有配置 onError 处理程序,则该错误将从此方法抛出。
  • 如果配置了 onError 处理程序,错误将被捕获并传递给处理程序,并且此方法将返回 undefined。
  • 可以使用 getErrorCount()getIsExecuting() 检查错误状态。

参数

args

...Parameters<TFn>

Returns (返回)

Promise<undefined | ReturnType<TFn>>

一个 Promise,它会解析为函数的返回值,如果错误被 onError 处理,则返回 undefined

Throws

如果没有配置 onError 处理程序,则为防抖函数抛出的错误

示例

ts
const debounced = asyncDebounce(async (value: string) => {
  const result = await saveToAPI(value);
  return result; // Return value is preserved
}, {
  wait: 1000,
  onError: (error) => {
    console.error('API call failed:', error);
  },
  throwOnError: true // Will both log the error and throw it
});

// Will only execute once, 1 second after the last call
// Returns the API response directly
const result = await debounced("third");
const debounced = asyncDebounce(async (value: string) => {
  const result = await saveToAPI(value);
  return result; // Return value is preserved
}, {
  wait: 1000,
  onError: (error) => {
    console.error('API call failed:', error);
  },
  throwOnError: true // Will both log the error and throw it
});

// Will only execute once, 1 second after the last call
// Returns the API response directly
const result = await debounced("third");
我们的合作伙伴
Code Rabbit
Unkey
订阅 Bytes

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

Bytes

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

订阅 Bytes

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

Bytes

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