본문으로 건너뛰기

클래스: AsyncBatcher<TValue>

정의 위치: async-batcher.ts:265

항목을 수집하고 비동기 방식으로 배치 단위로 처리하는 클래스입니다.

비동기 버전과 동기 버전: 비동기 버전은 동기 Batcher보다 다음과 같은 고급 기능을 제공합니다.

  • 배치 결과를 기다릴 수 있는 Promise를 반환합니다
  • AsyncRetryer 통합을 통한 재시도 지원이 내장되어 있습니다
  • 진행 중인 배치 실행을 중단하는 기능을 지원합니다
  • 대기 중인 배치가 시작되지 않도록 취소하는 기능을 지원합니다
  • onError 콜백과 throwOnError 제어를 통한 포괄적인 오류 처리를 제공합니다
  • 실행을 상세히 추적합니다(성공/오류/처리 완료 횟수)

비동기 기능, 반환값 또는 실행 제어가 필요하지 않다면 동기 Batcher가 더 가볍고 간단합니다.

배칭이란? 배칭은 여러 작업을 하나로 묶어 단일 단위로 처리하는 기법입니다.

AsyncBatcher는 다음 항목을 구성할 수 있는 유연한 비동기 배칭 구현 방법을 제공합니다.

  • 최대 배치 크기(배치당 항목 수)
  • 시간 기반 배칭(X밀리초 후 처리)
  • getShouldExecute를 통한 사용자 정의 배치 처리 로직
  • 배치 작업을 모니터링하는 이벤트 콜백
  • 실패한 배치 작업의 오류 처리

오류 처리:

  • onError 핸들러를 제공하면 오류, 실패한 항목의 배치, AsyncBatcher 인스턴스를 인수로 호출합니다
  • throwOnError가 true이면(onError 핸들러가 없을 때의 기본값) 오류를 던집니다
  • throwOnError가 false이면(onError 핸들러가 있을 때의 기본값) 오류를 무시합니다
  • onError와 throwOnError를 함께 사용할 수 있으며, 오류를 던지기 전에 핸들러를 호출합니다
  • AsyncBatcher 인스턴스로 오류 상태를 확인할 수 있습니다

상태 관리:

  • 반응형 상태 관리에 TanStack Store를 사용합니다
  • AsyncBatcher를 생성할 때 initialState로 초기 상태 값을 제공합니다
  • onSuccess 콜백으로 배치 실행 성공에 반응하고 사용자 정의 로직을 구현합니다
  • onError 콜백으로 배치 실행 오류에 반응하고 사용자 정의 오류 처리를 구현합니다
  • onSettled 콜백으로 배치 실행 완료(성공 또는 오류)에 반응하고 사용자 정의 로직을 구현합니다
  • onExecute 콜백으로 배치 실행에 반응하고 사용자 정의 로직을 구현합니다
  • onItemsChange 콜백으로 AsyncBatcher에서 항목이 추가되거나 제거될 때 반응합니다
  • 상태에는 처리된 전체 항목 수, 성공/오류 횟수, 실행 상태가 포함됩니다
  • 클래스를 직접 사용할 때는 asyncBatcher.store.state를 통해 상태에 접근할 수 있습니다
  • 프레임워크 어댑터(React/Solid)를 사용할 때는 asyncBatcher.state에서 상태에 접근합니다

예시

const batcher = new AsyncBatcher<number>(
async (items) => {
const result = await processItems(items);
console.log('Processing batch:', items);
return result;
},
{
maxSize: 5,
wait: 2000,
onSuccess: (result) => console.log('Batch succeeded:', result),
onError: (error) => console.error('Batch failed:', error)
}
);

batcher.addItem(1);
batcher.addItem(2);
// After 2 seconds or when 5 items are added, whichever comes first,
// the batch will be processed and the result will be available
// batcher.execute() // manually trigger a batch

타입 매개변수

TValue

TValue

생성자

생성자

new AsyncBatcher<TValue>(fn, initialOptions): AsyncBatcher<TValue>;

정의 위치: async-batcher.ts:277

매개변수

fn

(items) => Promise&lt;any>

initialOptions

AsyncBatcherOptions&lt;TValue>

반환값

AsyncBatcher&lt;TValue>

속성

asyncRetryers

asyncRetryers: Map<number, AsyncRetryer<(items) => Promise<any>>>;

정의 위치: async-batcher.ts:271


fn()

fn: (items) => Promise<any>;

정의 위치: async-batcher.ts:278

매개변수

items

TValue[]

반환값

Promise&lt;any>


key

key: string | undefined;

정의 위치: async-batcher.ts:269


options

options: AsyncBatcherOptionsWithOptionalCallbacks<TValue>;

정의 위치: async-batcher.ts:270


store

readonly store: Store<Readonly<AsyncBatcherState<TValue>>>;

정의 위치: async-batcher.ts:266

메서드

abort()

abort(): void;

정의 위치: async-batcher.ts:494

내부 중단 컨트롤러를 사용하여 진행 중인 모든 실행을 중단합니다. 아직 시작되지 않은 대기 중인 실행은 취소하지 않습니다. 항목은 제거하지 않습니다.

반환값

void


addItem()

addItem(item): Promise<any>;

정의 위치: async-batcher.ts:346

AsyncBatcher에 항목을 추가합니다 배치 크기에 도달하거나 타임아웃이 발생하거나 shouldProcess가 true를 반환하면 배치를 처리합니다

매개변수

item

TValue

반환값

Promise&lt;any>

배치 함수의 결과입니다. 오류가 발생하고 onError에서 처리한 경우에는 undefined입니다

발생 오류

onError 핸들러가 구성되지 않았거나 throwOnError가 true인 경우 배치 함수에서 발생한 오류입니다


cancel()

cancel(): void;

정의 위치: async-batcher.ts:507

아직 시작되지 않은 대기 중인 실행을 모두 취소합니다. 이미 진행 중인 실행은 중단하지 않습니다. 항목은 제거하지 않습니다.

반환값

void


clear()

clear(): void;

정의 위치: async-batcher.ts:455

AsyncBatcher에서 모든 항목을 제거합니다

반환값

void


flush()

flush(): Promise<any>;

정의 위치: async-batcher.ts:429

현재 항목 배치를 즉시 처리합니다

반환값

Promise&lt;any>


getAbortSignal()

getAbortSignal(executeCount?): AbortSignal | null;

정의 위치: async-batcher.ts:483

특정 실행의 AbortSignal을 반환합니다. executeCount를 제공하지 않으면 가장 최근 실행의 시그널을 반환합니다. 실행을 찾을 수 없거나 현재 실행 중이 아니면 null을 반환합니다.

매개변수

executeCount?

number

시그널을 가져올 특정 실행을 선택적으로 지정합니다

반환값

AbortSignal | null

예시

const batcher = new AsyncBatcher(
async (items: string[]) => {
const signal = batcher.getAbortSignal()
if (signal) {
const response = await fetch('/api/batch', {
method: 'POST',
body: JSON.stringify(items),
signal
})
return response.json()
}
},
{ maxSize: 10, wait: 100 }
)

peekAllItems()

peekAllItems(): TValue[];

정의 위치: async-batcher.ts:437

AsyncBatcher에 있는 모든 항목의 복사본을 반환합니다

반환값

TValue[]


peekFailedItems()

peekFailedItems(): TValue[];

정의 위치: async-batcher.ts:441

반환값

TValue[]


reset()

reset(): void;

정의 위치: async-batcher.ts:517

AsyncBatcher 상태를 기본값으로 재설정합니다

반환값

void


setOptions()

setOptions(newOptions): void;

정의 위치: async-batcher.ts:305

AsyncBatcher 옵션을 업데이트합니다

매개변수

newOptions

Partial&lt;AsyncBatcherOptions&lt;TValue>>

반환값

void