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

Async Generators vs Promise Arrays

Compare async generators to Promise.all patterns and understand when each approach is more appropriate.

Async Generators vs Promise Arrays

What you'll learn: When to use async generators versus Promise.all() or Promise.allSettled() for handling multiple asynchronous operations.

The Core Difference

Both async generators and Promise arrays handle multiple async operations, but they differ fundamentally in timing and memory usage.

Promise arrays (Promise.all, Promise.allSettled) load all promises immediately and wait for results in parallel. Think of it like ordering everything on a restaurant menu at once—you get it all together, but the kitchen must prepare everything upfront.

Async generators produce values one at a time, on demand. Like a streaming service, they deliver content as you consume it, not all at once.

When to Use Each

Use Promise arrays when:

  • You need all results together before proceeding
  • The dataset is small and finite
  • Parallel execution is critical for performance
  • Memory isn't a concern
// Good: fetching a small, fixed set
const users = await Promise.all([
  fetch('/user/1'),
  fetch('/user/2'),
  fetch('/user/3')
]);

Use async generators when:

  • Processing large or potentially infinite sequences
  • You want to start working with early results immediately
  • Memory efficiency matters (don't load everything at once)
  • You need backpressure control
// Good: streaming large dataset
async function* fetchPages() {
  for (let page = 1; page <= 1000; page++) {
    yield await fetch(`/data?page=${page}`);
  }
}

for await (const response of fetchPages()) {
  // Process each page as it arrives
}

Key Takeaway: Use Promise arrays for small, parallel batch operations where you need all results together; use async generators for large, sequential streams where memory efficiency and progressive processing matter.