Course contentsShow
← JavaScript
Lesson 2029 of 2,72342. Iteration Protocols Deep DiveFree lesson

When and Why For-Await-Of Exists

Understand the motivation behind for-await-of: iterating over async iterables that yield promises or async data sources.

When and Why For-Await-Of Exists

What you'll learn: You'll understand why JavaScript introduced for-await-of to elegantly iterate over async iterables that produce promises or data over time.

The Problem It Solves

You already know that Symbol.asyncIterator enables objects to produce values asynchronously—each next() call returns a promise that resolves to { value, done }. But using a regular for-of loop won't work because it expects synchronous values immediately, not promises.

Analogy: Imagine a conveyor belt delivering packages (values) at irregular intervals. A regular for-of loop is like someone expecting packages to already be there, grabbing instantly. An async iterable is like packages arriving eventually. You need a special way to wait for each package—that's for-await-of.

Why For-Await-Of Was Created

The for-await-of loop lets you iterate over objects with Symbol.asyncIterator by automatically awaiting each promise returned from next(). It unpacks the async iteration protocol into clean, readable syntax:

// Without for-await-of (manual and verbose):
const iterator = asyncIterable[Symbol.asyncIterator]();
let result = await iterator.next();
while (!result.done) {
  console.log(result.value);
  result = await iterator.next();
}

// With for-await-of (elegant):
for await (const value of asyncIterable) {
  console.log(value);
}

When You Need It

Use for-await-of when:

  • Working with async iterables (ReadableStreams, custom async data sources)
  • Iterating over data that arrives over time
  • Processing promises sequentially from an async generator

Key Takeaway: for-await-of exists to provide clean, readable syntax for iterating over async iterables, automatically awaiting each promised value so you can focus on processing data instead of manual promise handling.