Async Iterators and Generators in JavaScript

Async Iterators and Generators in JavaScript

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

const asyncIterable = { [Symbol.asyncIterator]() { let i = 0; return { async next() { if (i < 3) { await new Promise(resolve => setTimeout(resolve, 1000)); // Simulate async work return { value: i++, done: false }; } else { return { done: true }; } } }; } }; (async () => { for await (const num of asyncIterable) { console.log(num); // Outputs 0, 1, 2 with a 1-second delay } })();

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

async function* asyncCounter() { for (let i = 1; i <= 3; i++) { await new Promise(resolve => setTimeout(resolve, 1000)); // Simulate delay yield i; } } (async () => { for await (const num of asyncCounter()) { console.log(num); // Outputs 1, 2, 3 with 1-second delay } })();

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

async function* fetchData() { let page = 1; while (page <= 3) { // Simulate paginated API const response = await fetch(`https://jsonplaceholder.typicode.com/posts?_page=${page}&_limit=5`); const data = await response.json(); yield data; page++; } } (async () => { for await (const posts of fetchData()) { console.log(posts); // Logs 5 posts per page } })();

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

async function* errorHandlingGenerator() { try { yield await Promise.reject("Something went wrong!"); // Simulated error } catch (error) { console.log("Caught:", error); } } (async () => { for await (const value of errorHandlingGenerator()) { console.log(value); } })();

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

async function* numbers() { yield 1; yield 2; } async function* combinedGenerator() { yield* numbers(); yield 3; } (async () => { for await (const num of combinedGenerator()) { console.log(num); // Outputs 1, 2, 3 } })();

Allows modular composition of generators.

🔹 6. Async Generators vs Regular Generators

FeatureRegular GeneratorsAsync Generators
Declarationfunction*async function*
Yieldyield valueawait yield value
Iterationfor...offor await...of
Use CaseSync data streamsAsync 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!

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close