Generator函数通过function*定义,调用后返回迭代器,使用next()方法可逐段执行,每次遇到yield暂停并返回值,再次调用继续执行,支持传参、提前结束和错误注入,适用于惰性求值与异步控制。

JavaScript 中的 Generator 函数是一种特殊函数,可以暂停和恢复执行。调用 Generator 函数会返回一个迭代器对象,通过该对象提供的方法来控制函数的执行。
调用 Generator 函数的基本方式
定义一个 Generator 函数使用 function* 语法:
function* myGenerator() {yield 1;
yield 2;
return 3;
}
调用它会返回一个迭代器:
const gen = myGenerator();使用 next() 方法逐步执行
Generator 最主要的方法是 next(),用于启动或恢复执行:
- 第一次调用 gen.next():执行到第一个 yield,返回
{ value: 1, done: false } - 第二次调用:执行到第二个 yield,返回
{ value: 2, done: false } - 第三次调用:执行完函数体,返回
{ value: 3, done: true }
示例:
console.log(gen.next()); // { value: 1, done: false }console.log(gen.next()); // { value: 2, done: false }
console.log(gen.next()); // { value: 3, done: true }
向 next() 传参
可以通过 next(value) 向 Generator 内部传递数据,这个值会成为上一个 yield 表达式的返回值:
function* genWithInput() {const a = yield 'input?';
console.log(a); // 接收 next 传入的值
}const g = genWithInput();
g.next(); // 启动,停在 yield 'input?'
g.next('hello'); // 将 'hello' 赋给变量 a
提前结束:return() 和 throw()
-
gen.return(value):立即结束 Generator,返回
{ value: value, done: true } - gen.throw(error):在暂停处抛出异常,可被内部 try/catch 捕获
示例:
gen.return(99); // { value: 99, done: true },后续 next 不再执行基本上就这些。Generator 的核心就是通过 next() 驱动执行,配合 yield 实现惰性求值、异步流程控制等高级用法。










