Async Iterators and Generators in JavaScript
Async Iterators and Async Generators allow working with asynchronous data streams using for await...of
loops. These are especially useful when dealing with real-time data, streaming APIs, and paginated responses.
🔹 1. Async Iterators (Symbol.asyncIterator
)
An async iterator follows the same concept as a regular iterator but returns Promises instead of values.
📝 Example: Custom Async Iterator
✔ Uses Symbol.asyncIterator
to define an async iterable object.
✔ The next()
method returns a Promise
that resolves asynchronously.
✔ Iterate using for await...of
.
🔹 2. Async Generators (async function*
)
An async generator is a special function that produces values asynchronously using yield
.
📝 Example: Async Generator with yield
✔ Uses async function*
to define an async generator.
✔ Pauses at yield
and resumes when next()
is called.
✔ Supports for await...of
for easy iteration.
🔹 3. Fetching API Data with Async Generators
Async generators are useful for fetching paginated data.
📝 Example: Fetching API Data with an Async Generator
✔ Ideal for streaming API results.
✔ Prevents blocking large amounts of data at once.
🔹 4. Error Handling in Async Generators
You can handle errors inside async generators using try...catch
.
📝 Example: Handling Errors
✔ Catches errors inside the generator.
✔ Ensures smooth execution despite failures.
🔹 5. Combining Async Generators with yield*
Just like synchronous generators, async generators can delegate using yield*
.
📝 Example: Delegating Async Generators
✔ Allows modular composition of generators.
🔹 6. Async Generators vs Regular Generators
Feature | Regular Generators | Async Generators |
---|---|---|
Declaration | function* | async function* |
Yield | yield value | await yield value |
Iteration | for...of | for await...of |
Use Case | Sync data streams | Async tasks (API calls, delays) |
🔹 7. Summary
✔ Async Iterators (Symbol.asyncIterator
) return Promises inside next()
.
✔ Async Generators (async function*
) allow await
inside yield
.
✔ Use for await...of
to loop over async data sources.
✔ Handle errors with try...catch
inside async generators.
✔ Useful for streaming, paginated data, and API fetching.
🚀 Async generators simplify handling asynchronous sequences in JavaScript!