클래스: AsyncThrottler<TFn>
정의 위치: async-throttler.ts:230
비동기 스로틀 함수를 생성하는 클래스입니다.
비동기 버전과 동기 버전: 비동기 버전은 동기 Throttler보다 다음과 같은 고급 기능을 제공합니다.
- 스로틀된 함수의 결과를 기다릴 수 있도록 프로미스를 반환합니다
- AsyncRetryer 통합을 통해 재시도를 기본으로 지원합니다
- 진행 중인 실행을 취소할 수 있는 중단 기능을 지원합니다
- 대기 중인 실행이 시작되지 않도록 하는 취소 기능을 지원합니다
- onError 콜백과 throwOnError 제어 기능으로 포괄적인 오류 처리를 제공합니다
- 실행을 상세히 추적합니다(성공/오류/완료 횟수)
- 진행 중인 실행이 완료될 때까지 기다린 후 다음 실행을 예약합니다
비동기 기능, 반환값 또는 실행 제어가 필요하지 않다면 동기 Throttler가 더 가볍고 간단합니다.
스로틀이란? 스로틀은 함수의 실행 빈도를 제한하여 지정된 시간 윈도우 안에서 한 번만 실행되도록 합니다. 호출할 때마다 지연 타이머를 재설정하는 디바운스와 달리, 스로틀은 호출 빈도와 관계없이 함수가 일정한 간격으로 실행되도록 보장합니다.
이는 API 호출의 요청률을 제한하거나 스크롤/크기 조정 이벤트를 처리하는 경우, 또는 최대 실행 빈도를 보장하려는 모든 상황에 유용합니다.
오류 처리:
onError핸들러를 제공하면 오류 및 스로틀러 인스턴스와 함께 호출됩니다throwOnError가 true이면(onError 핸들러를 제공하지 않았을 때의 기본값) 오류를 던집니다throwOnError가 false이면(onError 핸들러를 제공했을 때의 기본값) 오류를 무시합니다- onError와 throwOnError를 함께 사용할 수 있으며, 오류를 던지기 전에 핸들러를 호출합니다
- 기반 AsyncThrottler 인스턴스를 사용하여 오류 상태를 확인할 수 있습니다
상태 관리:
- 반응형 상태 관리에 TanStack Store를 사용합니다
- 비동기 스로틀러를 생성할 때
initialState를 사용하여 초기 상태 값을 제공합니다 onSuccess콜백을 사용하여 함수 실행 성공에 반응하고 사용자 정의 로직을 구현합니다onError콜백을 사용하여 함수 실행 오류에 반응하고 사용자 정의 오류 처리를 구현합니다onSettled콜백을 사용하여 함수 실행 완료(성공 또는 오류)에 반응하고 사용자 정의 로직을 구현합니다- 상태에는 오류 횟수, 실행 상태, 마지막 실행 시각, 성공/완료 횟수가 포함됩니다
- 클래스를 직접 사용할 때는
asyncThrottler.store.state를 통해 상태에 접근할 수 있습니다 - 프레임워크 어댑터(React/Solid)를 사용할 때는
asyncThrottler.state에서 상태에 접근합니다
예시
const throttler = new AsyncThrottler(async (value: string) => {
const result = await saveToAPI(value);
return result; // Return value is preserved
}, {
wait: 1000,
onError: (error) => {
console.error('API call failed:', error);
}
});
// Will only execute once per second no matter how often called
// Returns the API response directly
const result = await throttler.maybeExecute(inputElement.value);
타입 매개변수
TFn
TFn extends AnyAsyncFunction
생성자
생성자
new AsyncThrottler<TFn>(fn, initialOptions): AsyncThrottler<TFn>;
정의 위치: async-throttler.ts:241
매개변수
fn
TFn
initialOptions
AsyncThrottlerOptions<TFn>
반환값
AsyncThrottler<TFn>
속성
asyncRetryers
asyncRetryers: Map<number, AsyncRetryer<TFn>>;
정의 위치: async-throttler.ts:236
fn
fn: TFn;
정의 위치: async-throttler.ts:242
key
key: string | undefined;
정의 위치: async-throttler.ts:234
options
options: AsyncThrottlerOptions<TFn>;
정의 위치: async-throttler.ts:235
store
readonly store: Store<Readonly<AsyncThrottlerState<TFn>>>;
정의 위치: async-throttler.ts:231
메서드
abort()
abort(): void;
정의 위치: async-throttler.ts:534
내부 중단 컨트롤러로 진행 중인 모든 실행을 중단합니다. 아직 시작되지 않은 대기 중인 실행은 취소하지 않습니다.
반환값
void
cancel()
cancel(): void;
정의 위치: async-throttler.ts:544
아직 시작되지 않은 대기 중인 모든 실행을 취소합니다. 이미 진행 중인 실행은 중단하지 않습니다.
반환값
void
flush()
flush(): Promise<Awaited<ReturnType<TFn>> | undefined>;
정의 위치: async-throttler.ts:463
현재 대기 중인 실행을 즉시 처리합니다
반환값
Promise<Awaited<ReturnType<TFn>> | undefined>
getAbortSignal()
getAbortSignal(maybeExecuteCount?): AbortSignal | null;
정의 위치: async-throttler.ts:524
특정 실행의 AbortSignal을 반환합니다. maybeExecuteCount를 제공하지 않으면 가장 최근 실행의 시그널을 반환합니다. 실행을 찾을 수 없거나 현재 실행 중이 아니면 null을 반환합니다.
매개변수
maybeExecuteCount?
number
시그널을 가져올 특정 실행을 선택적으로 지정합니다
반환값
AbortSignal | null
예시
const throttler = new AsyncThrottler(
async (data: string) => {
const signal = throttler.getAbortSignal()
if (signal) {
const response = await fetch('/api/save', {
method: 'POST',
body: data,
signal
})
return response.json()
}
},
{ wait: 1000 }
)
maybeExecute()
maybeExecute(...args): Promise<Awaited<ReturnType<TFn>> | undefined>;
정의 위치: async-throttler.ts:337
스로틀된 함수의 실행을 시도합니다. 실행 동작은 스로틀러 옵션에 따라 달라집니다.
-
마지막 실행 후 충분한 시간이 지났다면(>= wait 기간):
- leading=true인 경우: 즉시 실행합니다
- leading=false인 경우: 다음 trailing 실행까지 기다립니다
-
wait 기간 안이라면:
- trailing=true인 경우: wait 기간이 끝날 때 실행되도록 예약합니다
- trailing=false인 경우: 실행을 폐기합니다
매개변수
args
...Parameters<TFn>
반환값
Promise<Awaited<ReturnType<TFn>> | undefined>
예시
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');
reset()
reset(): void;
정의 위치: async-throttler.ts:558
디바운서 상태를 기본값으로 재설정합니다
반환값
void
setOptions()
setOptions(newOptions): void;
정의 위치: async-throttler.ts:269
비동기 스로틀러 옵션을 업데이트합니다
매개변수
newOptions
Partial<AsyncThrottlerOptions<TFn>>
반환값
void