生成器是可暂停和恢复执行的特殊函数,调用后返回实现迭代器协议的生成器对象;通过function*声明、yield暂停、next()驱动,适合懒求值、状态机与异步流程控制。
Generator(生成器)是 JavaScript 中一种特殊的函数,它能**暂停和恢复执行**,每次调用 next() 方法时返回一个 { value, done } 对象,适合按需生成数据、实现协程或处理异步流程。
在普通函数关键字 function 后加一个星号 *,函数体内使用 yield 暂停执行并输出值。
function* myGenerator() { yield 1; yield 2; }
const gen = function*() { yield 'a'; yield 'b'; };
const obj = { *gen() { yield 1; } };
class C { *gen() { yield 'hello'; } }
调用生成器函数**不会立即执行**,而是返回一个生成器对象(Generator Object),它实现了迭代器协议,拥有 next()、return()、throw() 方法。
gen().next() 开始执行,直到遇到第一个 yield 或函数结束next() 会从上次暂停位置继续执行done 变为 true,value 是 return 的值(或 undefined)yie 是暂停点,可多次出现;
ldreturn 是终止点,执行后生成器状态变为 done: true。
yield 10 → 返回 { value: 10, done: false }
return 'end' → 返回 { value: 'end', done: true }
return,默认返回 { value: undefined, done: true }
生成器天然适合做懒求值序列、状态机、异步控制流(配合 co 或 async/await 原理)。
function* naturals() { let i = 0; while (true) yield i++; }
function* walk(node) { if (!node) return; yield node.value; yield* walk(node.left); yield* walk(node.right); }
function* fetchFlow() { const a = yield fetch('/a'); const b = yield fetch('/b'); return [a, b]; }
基本上就这些。掌握 function*、yield、next() 三个核心,就能用好生成器。不复杂但容易忽略它的“可暂停”本质——它不是一次性算完,而是一步一取。