function asyncDebounce<TFn>(fn, initialOptions): (...args) => Promise<undefined | ReturnType<TFn>>
function asyncDebounce<TFn>(fn, initialOptions): (...args) => Promise<undefined | ReturnType<TFn>>
创建一个异步防抖函数,它会延迟执行直到指定的等待时间过去。只有当在等待期间没有新的调用时,防抖函数才会执行一次。如果在等待期间再次调用,计时器将重置,并开始一个新的等待周期。
与非异步 Debouncer 不同,此异步版本支持从防抖函数返回值的,这使其成为 API 调用和其他异步操作的理想选择,在这种情况下,您希望从 maybeExecute 调用中获取结果,而不是在防抖函数内部将结果设置到状态变量中。
错误处理
状态管理
• TFn extends AnyAsyncFunction
TFn
Function
尝试执行防抖函数。如果已有调用正在进行,它将被加入队列。
错误处理
...Parameters<TFn>
Promise<undefined | ReturnType<TFn>>
一个 Promise,它会解析为函数的返回值,如果错误被 onError 处理,则返回 undefined
如果没有配置 onError 处理程序,则为防抖函数抛出的错误
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");
您的每周 JavaScript 资讯。每周一免费发送给超过 10 万开发者。