使用 Azure 服務時,您通常需要處理大量數據集。 適用於 JavaScript 的 Azure SDK 提供異步反覆運算器,協助有效率地管理這項工作。 本文說明什麼是異步反覆運算器、如何使用它們,並提供重要 Azure 服務的範例。
什麼是異步反覆運算器?
異步反覆運算器是新式 JavaScript 中的一項功能,可讓您以異步方式取用數據。 它們適用於處理來自 API 的編頁數據。 異步反覆運算器會使用 for-await-of 迴圈逐一查看數據,並視需要擷取數據。
使用異步反覆運算器提供數個優點:
-
簡化的語法:
for-await-of迴圈使得使用非同步迭代器變得簡單明瞭。 - 隨選數據擷取: 只擷取您需要的數據,減少後端的記憶體使用量和負載。
- 未來的相容性: 異步反覆運算器是 JavaScript 中的標準功能,可確保與未來的更新和連結庫相容。
如果您不熟悉異步反覆運算器,下列概念有助於瞭解 Paging 如何在適用於 JavaScript 的 Azure SDK 中運作。
- 非同步函式:會傳回
Promise的函式。 - 生成器: 能夠暫停和恢復的函式,產生多個值。
- 異步產生器: 結合異步函式和產生器的功能,以產生異步反覆運算器。
Azure 用戶端連結庫會使用異步反覆運算器來處理可能龐大的數據集合。 以下是如何搭配各種 Azure 服務使用異步反覆運算器的範例。
迴圈遍歷幾個項目
如果您的結果集合只有少數項目,您可以遍歷該短清單。 下列程式代碼會在 Azure 儲存體中對一些小型容器進行迴圈操作:
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}`
);