> ## Documentation Index
> Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
> Use this file to discover all available pages before exploring further.

# JavaScript Async Generator Function

An asynchronous generator function is a special type of function declared with `async function*` that combines the pausing execution context of a generator with the asynchronous resolution of an `async` function. When invoked, it does not execute its body immediately; instead, it returns an `AsyncGenerator` object, which implements both the Async Iterator and Async Iterable protocols.

## Syntax

```javascript theme={"dark"}
async function* asyncGeneratorName([param[, param[, ...param]]]) {
  statements
}
```

## Core Mechanics

An async generator function allows the use of both `await` and `yield` keywords within its body.

1. **`await`**: Pauses the internal execution of the generator until a given `Promise` settles.
2. **`yield`**: Pauses the generator and emits a value. If a Promise is passed to `yield`, the async generator implicitly `await`s it before emitting the resolved value. It never yields a Promise directly to the consumer.

Unlike synchronous generators where calling `.next()` returns a raw `IteratorResult` object (`{ value, done }`), calling `.next()` on an `AsyncGenerator` returns a **`Promise`** that resolves to an `IteratorResult` object.

## Execution and Consumption

Because the `AsyncGenerator`'s `.next()` method returns a Promise, it must be consumed asynchronously. This is typically done using the `for await...of` statement or by manually resolving the Promises returned by `.next()`.

### Manual Iteration

```javascript theme={"dark"}
async function* asyncCounter() {
  await new Promise(resolve => setTimeout(resolve, 100)); // Internal async pause
  yield 1;
  yield 2;
}

const iterator = asyncCounter();

// .next() returns a Promise resolving to an IteratorResult
iterator.next().then(result => console.log(result)); // { value: 1, done: false }
iterator.next().then(result => console.log(result)); // { value: 2, done: false }
iterator.next().then(result => console.log(result)); // { value: undefined, done: true }
```

### Protocol Iteration (`for await...of`)

The `for await...of` statement automatically handles the resolution of the Promises returned by the `AsyncGenerator`'s `.next()` method, extracting the `value` and terminating when `done: true` is reached.

```javascript theme={"dark"}
async function consumeAsyncGenerator() {
  const iterator = asyncCounter();
  
  for await (const value of iterator) {
    console.log(value); // Logs 1, then 2
  }
}
```

## Delegation with `yield*`

The `yield*` expression in an async generator delegates execution to another iterable. In an `async function*`, `yield*` can delegate to both **Async Iterables** (like other async generators) and **Synchronous Iterables** (like Arrays or Sets).

```javascript theme={"dark"}
async function* subGenerator() {
  yield 'b';
}

async function* mainGenerator() {
  yield 'a';
  yield* subGenerator(); // Delegates to an Async Iterable
  yield* ['c', 'd'];     // Delegates to a Sync Iterable
}

// Consumption will yield: 'a', 'b', 'c', 'd'
```

## Error Handling and Control Flow

The `AsyncGenerator` object provides `.throw()` and `.return()` methods, which also return Promises.

* **`iterator.throw(error)`**: Injects an exception into the generator at the current suspended `yield` expression. If the generator has a `try...catch` block around the `yield`, it can catch the error and continue. If the injected error is uncaught, the Promise returned by the **`.throw()`** method itself rejects, and the generator is permanently closed. Any subsequent calls to `.next()` will simply return a Promise that resolves to `{ value: undefined, done: true }`.
* **`iterator.return(value)`**: Prematurely terminates the generator. It returns a Promise that resolves to `{ value: providedValue, done: true }` and triggers the execution of any pending `finally` blocks inside the generator.

```javascript theme={"dark"}
async function* errorHandlingGenerator() {
  try {
    yield 1;
    yield 2;
  } catch (err) {
    yield `Caught: ${err.message}`;
  }
}

const gen = errorHandlingGenerator();
gen.next().then(console.log); // { value: 1, done: false }

// Injects an error, which is caught internally
gen.throw(new Error("Halt")).then(console.log); // { value: 'Caught: Halt', done: false }

// Generator is now closed because it exited the try/catch block
gen.next().then(console.log); // { value: undefined, done: true }
```

<div
  style={{ 
display: "flex", 
justifyContent: "space-between", 
alignItems: "center", 
maxWidth: "754px", 
padding: "1rem 0",
marginBottom: "24px"
}}
>
  <span style={{ fontWeight: "bold", fontSize: "1.25rem", color: "var(--tw-prose-headings)", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif" }}>Tired of Poor JavaScript Skills? Fix That With Deep Grasping!</span>

  <a
    href="https://syntblaze.com"
    target="_blank"
    style={{ 
  marginLeft: "24px",
  textDecoration: "none", 
  backgroundColor: "#007AFF",
  color: "#ffffff", 
  padding: "6px 16px", 
  borderRadius: "16px",
  fontSize: "0.9rem",
  fontWeight: "600",
  textAlign: "center",
  transition: "background-color 0.2s ease"
}}
  >
    Learn More
  </a>
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/skill-tracking.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=b9b0305c93bb501c9e767b5c76c88835" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/skill-tracking.png" />

  <img src="https://mintcdn.com/syntblazellc/23tyuOzaWS88qFlc/images/nuggets.png?fit=max&auto=format&n=23tyuOzaWS88qFlc&q=85&s=c86c80197299762989e9b882419b2109" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/nuggets.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/bite-sized-exercises.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=a65f9a38c37ff28ab73ed783c53c60e3" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/bite-sized-exercises.png" />
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginTop: "12px" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/mastery-chain.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=748a1763454713e679260fbb95f154a2" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/mastery-chain.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-previews.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=242f61448ff5dd6deaaab2dccc13b507" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-previews.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-explanations.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=cf0fc1c31f9cd0fc26716781be05fbc9" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-explanations.png" />
</div>
