Azure サービスを使用する場合、多くの場合、大量のデータ セットを処理する必要があります。 Azure SDK for JavaScript には、このタスクを効率的に管理するための非同期反復子が用意されています。 この記事では、非同期反復子の概要、その使用方法、および主要な 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}`);
}
}
}
ループを続行する
ループの再開など、ループをより詳細に制御する必要がある場合は、継続トークンを使用します。 ページングイテレーターは、継続トークンからの再開もサポートします。 次の例では、最初のイテレーションの継続トークンを使用して、2 番目のページでイテレーションを再開します。
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}`
);