> ## 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.

# TypeScript For-await-of Loop

The `for-await-of` statement creates a loop that iterates over asynchronous iterable objects—objects that implement the `[Symbol.asyncIterator]()` method. It sequentially pauses the execution of the containing `async` function or block at the loop header until each yielded Promise resolves, extracting the fulfilled value into the loop variable before executing the block.

```typescript theme={"dark"}
// Execution pauses at the loop header until the current iteration's Promise resolves
for await (const variable of iterable) {
  // By the time execution reaches here, 'variable' contains the resolved value
}
```

## Technical Mechanics

Under the hood, the `for-await-of` loop interacts with the `AsyncIterator` protocol. When the loop initializes, it calls the `[Symbol.asyncIterator]()` method on the target object to retrieve an asynchronous iterator.

During each iteration:

1. The loop invokes the `next()` method on the iterator.
2. `next()` returns a `Promise<IteratorResult<T>>`.
3. The loop implicitly `await`s this Promise at the loop header.
4. Upon resolution, if the `IteratorResult` has `done: false`, the `value` property is assigned to the loop variable, and the block executes.
5. If the `IteratorResult` has `done: true`, the loop terminates.

## TypeScript Typing

TypeScript strictly types the `for-await-of` loop using the built-in `AsyncIterable<T>` and `AsyncIterator<T>` interfaces. The loop variable's type is automatically inferred based on the generic type parameter `T` of the iterable.

```typescript theme={"dark"}
// The generator returns an AsyncGenerator<number, void, unknown>
// which implements AsyncIterable<number>
async function* generateAsyncNumbers(): AsyncGenerator<number> {
  yield Promise.resolve(1);
  yield Promise.resolve(2);
}

async function processNumbers() {
  // TypeScript infers 'num' as type 'number'
  for await (const num of generateAsyncNumbers()) {
    console.log(num);
  }
}
```

### Synchronous Iterable Fallback

If the target object does not implement `[Symbol.asyncIterator]()` but does implement the synchronous `[Symbol.iterator]()` (such as a standard `Array`), `for-await-of` will consume the synchronous iterable. If the synchronous iterable yields Promises (e.g., `Iterable<Promise<T>>`), the loop will await each Promise sequentially.

```typescript theme={"dark"}
const promiseArray: Iterable<Promise<string>> = [
  Promise.resolve("A"),
  Promise.resolve("B")
];

async function processPromises() {
  // TypeScript infers 'char' as type 'string', unwrapping the Promise
  for await (const char of promiseArray) {
    console.log(char);
  }
}
```

## Compiler Configuration

To use `for-await-of` in TypeScript, specific `tsconfig.json` compiler options must be configured depending on your target environment:

* **`lib`**: Must include `"ES2018.AsyncIterable"` (or a broader library like `"ES2018"`) to provide the global type definitions for `Symbol.asyncIterator`, `AsyncIterable`, and `AsyncIterator`.
* **`target`**: If set to `"ES2018"` or higher, TypeScript emits native `for-await-of` syntax. If targeting older environments (such as `"ES5"` or `"ES6"`), TypeScript automatically downlevels the loop using the `__asyncValues` helper function.
* **Downleveling**: Unlike synchronous iteration (`for...of`), `for-await-of` does *not* require the `"downlevelIteration": true` flag to be downleveled. TypeScript always transpiles it when targeting pre-ES2018 environments. However, a runtime polyfill for `Symbol.asyncIterator` must be present in the execution environment for the emitted code to function correctly.

<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 TypeScript 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>
