Azure 서비스를 사용할 때는 대용량 데이터 집합을 처리해야 하는 경우가 많습니다. JavaScript용 Azure SDK는 이 작업을 효율적으로 관리하는 데 도움이 되는 비동기 반복기를 제공합니다. 이 문서에서는 비동기 반복기의 정의, 사용 방법을 설명하고 주요 Azure 서비스에 대한 예제를 제공합니다.
비동기 반복기란?
비동기 반복기는 데이터를 비동기적으로 사용할 수 있는 최신 JavaScript의 기능입니다. API에서 페이지를 매긴 데이터를 처리하는 데 유용합니다. 비동기 반복기는 for-await-of
루프를 사용하여 데이터를 필요에 따라 반복적으로 가져옵니다.
비동기 반복기를 사용하면 다음과 같은 몇 가지 이점이 있습니다.
-
간소화된 구문: 이
for-await-of
루프를 사용하면 비동기 반복기를 간단하게 사용할 수 있습니다. - 주문형 데이터 페치: 필요한 데이터만 가져와 메모리 사용량을 줄이고 백 엔드에 로드합니다.
- 향후 호환성: 비동기 반복기는 JavaScript의 표준 기능으로 향후 업데이트 및 라이브러리와의 호환성을 보장합니다.
비동기 반복기를 처음으로 사용하는 경우 다음 개념은 JavaScript용 Azure SDK에서 페이징이 작동하는 방식을 이해하는 데 도움이 됩니다.
-
비동기 함수:
Promise
를 반환하는 함수. - 발전기: 일시 중지하고 다시 시작하여 여러 값을 생성할 수 있는 함수입니다.
- 비동기 생성기: 비동기 함수와 생성기의 기능을 결합하여 비동기 반복기를 생성합니다.
Azure 클라이언트 라이브러리는 비동기 반복기를 사용하여 잠재적으로 큰 데이터 컬렉션을 처리합니다. 다음은 다양한 Azure 서비스에서 비동기 반복기를 사용하는 방법의 예입니다.
몇 가지 항목 반복
결과 집합이 몇 개의 항목만 있는 경우 해당 작은 목록을 반복할 수 있습니다. 다음 코드는 Azure Storage의 작은 컨테이너 집합을 반복합니다.
for await (const container of blobServiceClient.listContainers()) {
console.log(`Container: ${container.name}`);
}
페이지별 데이터 반복
데이터 집합이 더 큰 경우 페이지에서 데이터를 반환한 다음 각 페이지의 항목을 반복할 수 있습니다. 코드가 페이지별로 데이터를 순환한 다음 각 항목을 처리합니다.
const firstPage = await blobServiceClient.listContainers().byPage().next();
const continuationToken = firstPage.value.continuationToken;
// The iterator also supports iteration by page.
for await (const page of blobServiceClient
.listContainers()
.byPage({ continuationToken })) {
if (page.containerItems) {
for (const container of page.containerItems) {
console.log(`Container: ${container.name}`);
}
}
}
계속 반복
루프 재개를 포함하여 루프를 더 많이 제어해야 하는 경우 연속 토큰을 사용합니다. 페이징된 반복기는 이어질 토큰에서 다시 시작하는 것을 지원합니다. 다음 예제에서는 첫 번째 반복의 연속 토큰을 사용하여 두 번째 페이지에서 반복을 다시 시작합니다.
console.log('Starting to process pages...');
let processingComplete = false;
let pageNumber = 1;
try {
let page = undefined;
let continuationToken = undefined;
do {
// Get a page of results
page = await blobServiceClient.listContainers().byPage().next();
// Get the continuation token from the current page
continuationToken = page?.value?.continuationToken;
console.log(
`Processing page ${pageNumber}, items ${page.value.containerItems?.length || 0} with continuation token: ${continuationToken || 'none'}`
);
console.log(page.value);
// Scenario to continue paging:
// Perform an operation on the current page results
// if the operation returns true, stop processing
processingComplete = await fakeProcessor(page.value);
if (processingComplete) {
console.log('Stopping processing.');
break;
}
console.log(
`Processing complete for page ${pageNumber++}: get next page if a continuation token exists`
);
} while (continuationToken && !processingComplete);
console.log(
`Finished processing. Total pages processed: ${pageNumber - 1}`
);