A common feature in cloud APIs is paging for list results. Result sets may be massive – you could have thousands of blobs in a container, for example. Getting all results at once can cause delays in transmission and excessive load on the backend, and might even be so big it won’t fit into memory in your client. So services offer potentially large collections in pages and developers request one page of results at a time.

The Azure SDK for Javascript and TypeScript abstracts away the details of requesting pages from the service. You write a normal loop, and we take care of the rest. For example, here is the code that iterates through a list of containers in Storage:

const containers = blobServiceClient.listContainers();
for await (const container of containers) {
  console.log(`Container: ${container.name}`);
}

How is this done? We use features that were added to recent editions of JavaScript; most notably async iterators. Async Iterators represent a stream of data that is loaded asynchronously. They are used across the Azure SDK to represent asynchronous streams of data such as paginated APIs like above.

Async Iterators, the Async Generators that produce them, and the for - await - of  loops loops that consume them were added in the ES2018 edition of the JavaScript standard. They are supported natively in recent version of modern browsers, but TypeScript can compile them down to previous versions of JavaScript.

If you’re already familiar with async functions, promises, generators, and iterators, feel free to skip the background below. If not, that’s great, most of this blog is for you!

#azure sdk #javascript #typescript #programming

Async Iterators in the Azure SDK for JavaScript/TypeScript
1.80 GEEK