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; // 返回值被保留
}, {
wait: 1000,
onError: (error) => {
console.error('API 调用失败:', error);
},
throwOnError: true // 将同时记录错误并抛出错误
});
// 仅在最后一次调用后 1 秒执行一次
// 直接返回 API 响应
const result = await debounced("third");
const debounced = asyncDebounce(async (value: string) => {
const result = await saveToAPI(value);
return result; // 返回值被保留
}, {
wait: 1000,
onError: (error) => {
console.error('API 调用失败:', error);
},
throwOnError: true // 将同时记录错误并抛出错误
});
// 仅在最后一次调用后 1 秒执行一次
// 直接返回 API 响应
const result = await debounced("third");