Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 18

Async Generators for Data Streams

This lesson is built with resources from youtube.com, javascript.info and 1 more site.

Hello! Welcome back to our module on Advanced Asynchronous Patterns.

In our last lesson, you successfully implemented the async iterator protocol manually. You created a PaginatedFetcher class that could fetch data page by page, all while managing the state (current page, item buffer) within the iterator's closure. It was a powerful demonstration of how to handle streaming data, but as you likely noticed, it involved a fair amount of boilerplate code.

Today, we'll build directly on that foundation to explore a much more elegant and powerful feature: async generators. Our goal is to create and consume async generators for asynchronous data streams. You'll see how the async function* syntax dramatically simplifies the code you wrote in the last lesson, allowing you to write complex asynchronous iteration logic in a clean, linear style.

Let's start with a visual representation of the clarity we're aiming for.

Async Generators vs Chained Promises
This image contrasts the complexity of deeply nested promise chains (left) with the clean, linear flow of processing data streams using async generators (right). Our goal is to master the pattern on the right.

1. From Manual Iterators to Async Generators

The core problem with manual async iterators is the same one we saw with synchronous iterators: you have to explicitly manage the state. An async generator, just like its synchronous counterpart, lets the JavaScript engine manage that state for you.

An async generator is created with the async function* syntax. This powerful combination gives you two abilities within the same function:

  1. You can use await to pause the function and wait for asynchronous operations (like fetch or setTimeout) to complete.
  2. You can use yield to pause the function and emit a value to the consumer.

The magic happens when you combine them: you can yield a value, await a promise, and then yield another value, all within what looks like simple, sequential code.

Async iteration and generators

The article 'Async iteration and generators' from javascript.info provides a concise introduction to the syntax and behavior of async generators.

Read the section titled 'Async generators (finally)'. Pay close attention to the generateSequence example. Notice how await and yield are used together. Also, note the technical difference mentioned: generator.next() now returns a promise.

The key takeaway is that an async generator function doesn't run to completion. It pauses at each yield statement, and the consumer can pull values from it one by one using a for await...of loop.


2. Why Use Async Generators? The Case for Streams

Before we dive deeper into implementation, it's crucial to understand why this pattern is so important. You might ask, "Why not just fetch all the data, put it in an array with Promise.all, and then process it?"

Given your background, you'll appreciate that the answer lies in scalability and memory efficiency. An array requires you to hold the entire dataset in memory at once. This is fine for a few hundred items, but it's completely unworkable for datasets that are gigabytes or even terabytes in size, or for logically infinite streams like a Twitter feed.

Async generators allow us to work with streams—sequences of data that arrive over time. We process one piece of data at a time, using minimal memory, and we can start processing the first item as soon as it arrives, without waiting for the entire set.

Using async generators to stream data in JavaScript

The video 'Using async generators to stream data in JavaScript' from Fun Fun Function gives an excellent explanation of why streams are a superior model for large datasets.

Watch from the beginning to 07:45. The speaker does a great job of framing the problem, moving beyond small datasets to a world of '30 gigabytes' or 'all the cat pictures in the world'. This section establishes the mental model for why we need streams and, by extension, async generators.


3. The "Aha!" Moment: Refactoring to an Async Generator

Now for the most satisfying part. We'll take the complex, manual async iterator for the Flickr API you saw in the last lesson and refactor it into a clean, concise async generator. This will make the benefit of the async function* syntax immediately obvious.

Using async generators to stream data in JavaScript

Continuing with the same Fun Fun Function video, we'll now see the refactoring in action. This is the core of today's lesson.

Watch from 18:15 to 24:32. The speaker takes the large, stateful manual iterator and rewrites it as an async generator. Pay close attention to how the while(true) loop, local pageIndex variable, await, and yield completely replace the previous complex structure. The side-by-side comparison at the end is particularly illuminating.

The difference is dramatic. All the manual state management (pageIndex, photoIndex, cache) disappears. The function's own local scope and execution context become the state. The code now reads as a simple description of the process: "in an infinite loop, fetch a page of data, then yield each item from that page." This is a massive improvement in readability and maintainability.


4. A Practical Application: Abstracting Paginated APIs

The most common use case for async generators is abstracting away the complexity of paginated APIs. You write a single async generator that handles the details of fetching page after page, and the rest of your application can consume the data with a simple for await...of loop, as if it were a plain array.

Let's look at another excellent, real-world example that fetches commits from the GitHub API.

Async iteration and generators

The javascript.info article provides a complete, practical example of this pattern.

Read the section 'Real-life example: paginated data'. Study the fetchCommits function. Note how the while (url) loop continues as long as the API provides a 'next' page link. Inside, it fetches data, yields the commits one by one, and then prepares for the next iteration. The calling code is beautifully simple.

Test your understanding!

In the previous lesson, you created a PaginatedFetcher class that implemented the async iterator protocol manually. Your task is to refactor that logic into a standalone async function*.

Instructions:
Rewrite the logic from the class-based PaginatedFetcher into a single async generator function called fetchPaginatedItems(baseUrl). This function should do the same thing: fetch pages of items until the API returns an empty array.

Here is the mock fetch and the testing code for reference. You only need to write the fetchPaginatedItems function.

// Mock fetch function to simulate API calls
async function mockFetch(url) {
  console.log(`Fetching: ${url}`);
  const urlParams = new URLSearchParams(url.split('?')[1]);
  const page = parseInt(urlParams.get('page')) || 1;

  if (page === 1) {
    return { json: () => Promise.resolve([{ id: 1 }, { id: 2 }]) };
  }
  if (page === 2) {
    return { json: () => Promise.resolve([{ id: 3 }]) };
  }
  return { json: () => Promise.resolve([]) }; // No more pages
}

// Your implementation here
async function* fetchPaginatedItems(baseUrl) {
  // ...
}


// --- Testing your implementation ---
(async () => {
  // The generator function returns an async iterable
  const items = fetchPaginatedItems('https://api.example.com/items');
  
  // We consume it with for await...of
  for await (const item of items) {
    console.log(item);
  }
  
  console.log('Done!');
})();

/*
Expected output:
Fetching: https://api.example.com/items?page=1
{ id: 1 }
{ id: 2 }
Fetching: https://api.example.com/items?page=2
{ id: 3 }
Fetching: https://api.example.com/items?page=3
Done!
*/
Show answer

Here's a concise implementation using an async generator:

async function* fetchPaginatedItems(baseUrl) {
  let page = 1;
  while (true) {
    const response = await mockFetch(`${baseUrl}?page=${page}`);
    const items = await response.json();

    if (items.length === 0) {
      // If the page is empty, we're done.
      break; 
    }

    // Yield each item from the current page
    for (const item of items) {
      yield item;
    }

    page++;
  }
}

Compare this to the manual implementation from the last lesson. It's significantly shorter and easier to understand. The while (true) loop and the page variable are the only state we need to track, and it's all contained neatly within the generator function's scope.


5. Composing Async Generators

The true power of this pattern emerges when you start composing generators. You can create utility functions that take an async iterable as input and return a new, transformed async iterable. This allows you to build declarative, functional-style processing pipelines for streams, much like you would use map, filter, and reduce on arrays.

How to consume a paginated API using JavaScript async ...

The article 'How to consume a paginated API using JavaScript async generators' by James Sinclair provides a superb walkthrough of building such a pipeline.

Read the sections 'Fetching search results', 'Filtering', and 'Deleting'. First, see how fetchAllToDosWithPrefix abstracts the pagination logic, just like our previous examples. Next, look at the filter function. It's a higher-order function that takes a predicate and returns a new async generator that yields only the matching items. Finally, examine the flatMap function. It introduces yield*, a crucial keyword for delegating iteration. It allows one generator to yield all the items from another iterable, which is essential for flattening results.

The concepts of filter and flatMap (yield*) are fundamental to building powerful, reusable stream-processing tools. This functional composition approach is highly valued in modern software engineering for its clarity and testability.


Conclusion

Today, you've bridged the gap between manual async iteration and the modern, generator-based approach. You've seen how async generators provide powerful syntactic sugar that makes working with asynchronous data streams clean, efficient, and intuitive.

Key Takeaways:

  • Async generators are defined with async function* and allow the use of both await and yield.
  • They are the preferred way to implement the async iterator protocol, eliminating manual state management.
  • Their primary use case is to create abstractions over streaming data sources like paginated APIs, allowing consumers to use a simple for await...of loop.
  • They are composable, enabling you to build functional-style data processing pipelines for asynchronous streams using helpers like map, filter, and flatMap (with yield*).

Next Up

We've used the for await...of loop extensively today as the primary consumer of async generators. In the next lesson, we will focus specifically on this loop structure. We'll explore its mechanics in more detail and see how it can be used to consume any async iterable, whether it's created by a generator or implemented manually.