什么是 Generator 函数?它和普通函数有什么不同?
请说明 Generator 函数的定义、特性(yield/next/return/throw),以及与普通函数的区别。
回答
Yahuda
Generator 函数:一种可以暂停和恢复执行的函数,通过 function* 定义。
特性:
function* gen() {
yield 1;
yield 2;
return 3;
}
const g = gen();
console.log(g.next()); // { value: 1, done: false }
console.log(g.next()); // { value: 2, done: false }
console.log(g.next()); // { value: 3, done: true }
console.log(g.next()); // { value: undefined, done: true }
与普通函数的区别:
| 特性 | Generator 函数 | 普通函数 |
|------|---------------|---------|
| 定义 | function* | function |
| 执行 | 惰性执行,调用 next() 时才运行到下一个 yield | 同步执行,调用即运行完毕 |
| 返回值 | 返回 Generator 对象(迭代器 + 可迭代) | 返回函数结果 |
| 状态保持 | 自动保持每次暂停的状态 | 执行后释放上下文 |
| yield | 可暂停并传出值 | 无 |
| next(arg) | 可从外部向函数内传值 | 无 |
| return(value) | 提前结束迭代 | 正常返回 |
| throw(err) | 在暂停处抛出异常 | 仅在函数体内捕获 |
双向通信:
function* ask() {
const answer = yield '问题?';
return `回答: ${answer}`;
}
const g = ask();
g.next(); // { value: '问题?', done: false }
g.next('42'); // { value: '回答: 42', done: true }
应用:异步流程控制(co 库)、生成无限序列、状态机、遍历器实现。