Generators and async functions are both special functions in JavaScript that handle paused and resumed execution, but they serve different purposes and work differently.
1️⃣ Generators
- Declared with
function*syntax - Can pause execution with
yieldand resume later - Useful for lazy iteration or custom iterators
- Returns an iterator object with
next()method
function* genNumbers() {
yield 1;
yield 2;
yield 3;
}
const gen = genNumbers();
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 }
✅ Key points:
- Execution pauses at
yield - Manual control with
next() - Synchronous by default (does not handle Promises automatically)
2️⃣ Async Functions
- Declared with
asynckeyword - Always return a Promise
- Execution pauses at
awaituntil the Promise resolves - Makes asynchronous code look synchronous
async function fetchData() {
const res = await fetch("https://api.example.com/data");
const data = await res.json();
return data;
}
fetchData().then(console.log);
✅ Key points:
- Handles async operations automatically
- No manual
next()calls - Execution pauses only at
await
3️⃣ Key Differences
| Feature | Generator | Async Function |
|---|---|---|
| Syntax | function* |
async function |
| Returns | Iterator | Promise |
| Execution | Paused/resumed with yield + next() |
Paused/resumed automatically with await |
| Purpose | Lazy iteration, custom iterators | Asynchronous programming (API calls, timers) |
| Handling Promises | Manual (can yield Promises) | Automatic, waits for Promise resolution |
4️⃣ Example Comparison
Generator:
function* asyncGen() {
const a = yield Promise.resolve(1);
const b = yield Promise.resolve(2);
return a + b;
}
- Must manually handle each
yieldvalue with.next()
Async Function:
async function asyncFunc() {
const a = await Promise.resolve(1);
const b = await Promise.resolve(2);
return a + b;
}
- Automatically waits for Promises, much simpler
⚡ In short:
Generators are for synchronous control flow and lazy iteration, manually paused with
yield.
Async functions are for asynchronous operations, automatically pausing atawaitand returning a Promise.
Generators give manual control, async functions give automatic async handling.