Hello! Welcome to the first lesson in our third module, "Advanced Asynchronous Patterns."
In the previous module, you mastered synchronous iteration. You learned how to make any custom object iterable by implementing the [Symbol.iterator] protocol manually and saw how function* generators provide a much more elegant syntax for the same task. The core pattern was always: an object provides an iterator, which you call next() on to get a sequence of { value, done } objects.
But what happens when the next value isn't available immediately? What if you need to fetch it from a network, read it from a file, or wait for a database query? Synchronous iteration breaks down here.
This is where our new topic begins. Today, we'll extend the iteration concepts you already know into the asynchronous world. Our goal is to implement the async iterator protocol for a custom data source. You will learn how to create iterable objects that produce values over time, allowing you to process data streams efficiently without blocking the event loop.
1. The Asynchronous Iteration Protocol
The need for asynchronous iteration arises from a fundamental challenge: data often arrives asynchronously. Imagine fetching a list of items from a paginated API. You get the first page now, but the second page requires another network request. A standard for...of loop can't wait for that request to complete.
JavaScript solves this with a parallel set of protocols for asynchronous iteration. The changes are direct analogies to the synchronous versions you're familiar with.
Async iteration and generators
To understand the core mechanics, we'll start with the article 'Async iteration and generators' from javascript.info. It provides a crystal-clear definition of the async iterator protocol.
Read the section titled 'Async iterables'. Focus on the three key differences it highlights between synchronous and asynchronous iterators, which are summarized in the table. Pay close attention to the example range object, noting how next() is now an async function and the loop uses for await...of.
As the article explains, the transition from synchronous to asynchronous iteration involves three key changes:
| Feature | Synchronous Iterators | Asynchronous Iterators |
|---|---|---|
| Protocol Symbol | Symbol.iterator |
Symbol.asyncIterator |
next() Return Value |
{ value, done } |
Promise which resolves to { value, done } |
| Consumer | for...of loop |
for await...of loop |
Let's break down the most crucial change: the next() method. By making it return a Promise, we give it the ability to perform asynchronous work (like fetch or setTimeout) and only deliver the value when it's ready. The for await...of loop is the corresponding syntax that knows how to "unwrap" these promises at each step of the iteration.
To see this transformation in action, let's look at another resource.
Understanding Async Iterators in JavaScript
The article 'Understanding Async Iterators in JavaScript' provides a very clear, side-by-side style comparison that solidifies the concept.
Read the section that begins with the heading 'In order to understand the concept of async iterators...'. First, review the simple synchronous iterator for an array. Then, observe how it's converted into an asyncIterator by changing the symbol and wrapping the next() method's return value in a Promise.
2. Implementing the Protocol for a Streaming Data Source
Now that you understand the theory, let's implement the protocol for a more realistic "custom data source": a streaming API. We'll simulate fetching data from a paginated API, a common task in web development.
Our data source will be a stream of cat pictures from the Flickr API. The key challenge is that we can't fetch all the pictures at once—there could be millions. We need to fetch them page by page, but provide them to the consumer of our iterator one by one. This is a perfect use case for async iteration.
Using async generators to stream data in JavaScript
The video 'Using async generators to stream data in JavaScript' from Fun Fun Function provides an excellent walk-through of a manual async iterator implementation. We'll focus on the first part, where the iterator is built by hand.
First, watch from 01:15 to 07:45. This section explains why streams and async iterators are necessary for large datasets. Then, watch the manual implementation from 12:06 to 18:15. As you watch, focus on these key aspects: The object returned by flickrTagSearch has a method named [Symbol.asyncIterator]. This makes it an async iterable. This method returns the iterator itself, an object with a next() method. The next() method contains the core logic: it manages state (pageIndex, photoIndex), fetches new pages when the local cache is empty, and returns a promise that resolves to the next photo.
The structure you just saw should feel familiar. It's the async version of the manual LinkedList iterator we built in the last module. State is managed within a closure, and the next() method manually controls the flow. The main difference is the use of await and the fact that next() is an async function.
To consume this async iterable, we use the for await...of loop. The following video explains how this new loop syntax works.
Async iterators (for await ... of) in JavaScript
In a related video, Fun Fun Function explains exactly how to consume an async iterable and what the for await...of syntax does under the hood.
Watch from 07:45 to 13:16. This segment shows: How to convert a synchronous next() to an async next(). How to use for await...of inside an async function to consume the results. A manual breakdown of what for await...of is doing: calling await iterator.next() in a loop.
This deconstruction is important. for await...of isn't magic; it's syntactic sugar for a loop that repeatedly calls await iterator.next() and processes the result until done is true.
3. A Class-Based Implementation
The factory function pattern shown in the video is effective, but in many codebases, you might prefer to encapsulate this logic within a class. This is especially useful for creating reusable components for data access.
Let's look at another real-world example: creating an async iterator for a database query result set.
Understanding Async Iterators in JavaScript
The 'dev.to' article we saw earlier demonstrates a practical, class-based approach. It creates a Cursor class to wrap a database result set from Node.js's Oracle driver.
Read the 'Usecases' section. Notice how the Cursor class is structured. It receives the resultSet in its constructor. The core logic resides in the _buildIterator method, which returns an iterator whose next method calls this.resultSet.getRow() (an async operation) and wraps the result in the expected { value, done } shape.
This Cursor class provides a clean API. A developer using it doesn't need to know about the underlying getRow() method; they can simply use for await...of on the iterable provided by cursor.getIterable(), abstracting away the implementation details of the database driver. This is a powerful abstraction pattern.
Now, let's put your knowledge to the test.
Test your understanding!
Your task is to create a PaginatedFetcher class that fetches items from a paginated API. The class should be asynchronously iterable.
Instructions:
- The
constructorshould accept abaseUrl(e.g.,'https://api.example.com/items'). - The class needs a
[Symbol.asyncIterator]method that returns an iterator object. - The iterator's
next()method must beasync. It should fetch pages of data using thefetchAPI. The URL for a given page should bethis.baseUrl + '?page=' + pageNumber. - To keep things simple, we'll use a mock
fetchfunction. - The iterator should manage its own state: the current page number, the items from the current page, and the index of the next item to yield. When it runs out of items on a page, it should fetch the next one.
- The API returns
[](an empty array) when there are no more pages. The iterator should detect this and return{ done: true }.
// 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;
// Simulate a paginated API
if (page === 1) {
return { json: () => Promise.resolve([{ id: 1 }, { id: 2 }]) };
}
if (page === 2) {
return { json: () => Promise.resolve([{ id: 3 }]) };
}
// Page 3 and beyond are empty
return { json: () => Promise.resolve([]) };
}
class PaginatedFetcher {
constructor(baseUrl) {
this.baseUrl = baseUrl;
}
// Your implementation here
[Symbol.asyncIterator]() {
// ...
}
}
// --- Testing your implementation ---
(async () => {
const fetcher = new PaginatedFetcher('https://api.example.com/items');
// This loop should work with your implementation
for await (const item of fetcher) {
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 one possible implementation:
class PaginatedFetcher {
constructor(baseUrl) {
this.baseUrl = baseUrl;
}
[Symbol.asyncIterator]() {
let currentPage = 1;
let itemBuffer = [];
let bufferIndex = 0;
return {
async next() {
// If we've exhausted the current buffer, fetch the next page
if (bufferIndex >= itemBuffer.length) {
const response = await mockFetch(`${this.baseUrl}?page=${currentPage}`);
const newItems = await response.json();
if (newItems.length === 0) {
// No more items on this page and all subsequent pages
return { done: true };
}
// Reset buffer and page state
itemBuffer = newItems;
bufferIndex = 0;
currentPage++;
}
// Yield the next item from the buffer
const item = itemBuffer[bufferIndex];
bufferIndex++;
return { value: item, done: false };
}
};
}
}
This solution correctly implements the protocol. The state (currentPage, itemBuffer, bufferIndex) is managed within the closure created by the [Symbol.asyncIterator] call. The next method contains the asynchronous logic to fetch and buffer data as needed.
Conclusion
In this lesson, you've taken a major step into advanced asynchronous JavaScript. You've seen that the iterator protocol you learned for synchronous code has a direct and powerful counterpart for the async world.
Key Takeaways:
- The async iterator protocol is designed for iterating over data sources that deliver values asynchronously, such as network streams or file I/O.
- It is defined by three components:
Symbol.asyncIterator, anext()method that returns aPromise, and thefor await...ofloop for consumption. - Manually implementing this protocol involves managing state (like page numbers or caches) and handling asynchronous operations within the
next()method. - This pattern allows you to create powerful abstractions, hiding the complexity of a streaming data source behind a simple, standard iteration interface.
Next Up
If you found the manual implementation a bit verbose and state-heavy, you're right! It has the same boilerplate issues as the manual synchronous iterators we saw before.
Fortunately, JavaScript provides a more elegant solution. In our next lesson, we will explore async generators. You will learn how async function* and yield can be used to write asynchronous iteration logic in a clean, linear style, dramatically simplifying the code you wrote today.