← JS Mastery | Module 7: ES6+ Modern JS Generators & Async Generators
Module 7

Generators & Async Generators

⏱ 22 min read ● Advanced 🆓 Free

Generator Functions

Generators are functions that can be paused (yield) and resumed. They implement the iterator protocol automatically, making it easy to create lazy sequences.

function* count(from, to) {
  for (let i = from; i <= to; i++) {
    yield i;  // pause and return value
  }
}

const gen = count(1, 3);
console.log(gen.next());  // { value: 1, done: false }
console.log(gen.next());  // { value: 2, done: false }
console.log(gen.next());  // { value: 3, done: false }
console.log(gen.next());  // { value: undefined, done: true }

// Use with for...of:
for (const n of count(1, 5)) console.log(n);

// Spread:
console.log([...count(1, 5)]);  // [1,2,3,4,5]

// Infinite generator — no stack overflow!
function* naturals() {
  let n = 0;
  while (true) yield n++;
}

function* take(gen, n) {
  let count = 0;
  for (const item of gen) {
    if (count++ >= n) return;
    yield item;
  }
}
console.log([...take(naturals(), 5)]);  // [0,1,2,3,4]

Async Generators

// Async generator — combine generators with async/await:
async function* paginate(url) {
  let page = 1;
  while (true) {
    const res = await fetch(url + "?page=" + page);
    const { data, hasMore } = await res.json();
    yield data;
    if (!hasMore) break;
    page++;
  }
}

// Consume with for await...of:
for await (const items of paginate("/api/items")) {
  console.log("Page:", items);
  if (shouldStop) break;
}

// Useful generators:
function* idGen(prefix = "id") {
  let n = 0;
  while (true) yield prefix + "-" + (++n);
}
const ids = idGen("user");
console.log(ids.next().value);  // "user-1"
console.log(ids.next().value);  // "user-2"

// Fibonacci:
function* fibonacci() {
  let [a, b] = [0, 1];
  while (true) {
    yield a;
    [a, b] = [b, a + b];
  }
}
console.log([...take(fibonacci(), 10)]);  // [0,1,1,2,3,5,8,13,21,34]

⚡ Key Takeaways

🎯 Practice Exercises

EXERCISE 1

Write generator functions for: range(start, end, step), repeat(value, times), zip(iter1, iter2). Test them with spread and for...of.

← Iterators