Generator 的 return() 方法可立即终止生成器并返回指定值,使其状态变为 completed;它跳过后续 yield,不再响应 next() 调用,且会触发外层 finally 块执行。

Generator 的 return() 方法可以立即终止生成器执行,并返回指定值,让其状态变为 "completed"。它不触发后续 yield,也不再响应 next() 调用(后续调用一律返回 {value: undefined, done: true})。
return() 的基本行为
return(value) 会:
- 立即中止生成器函数的执行(跳过当前及之后所有
yield) - 将传入的
value作为返回对象的value字段 - 设置返回对象的
done为true - 此后所有
next()、throw()、return()调用都返回{value: undefined, done: true}
与 yield 和 throw 的交互
return() 不会进入 try...finally 块中的 finally(除非生成器正在暂停于 try 中且尚未退出),但会执行外层 finally(如果有的话):
function* g() {
try {
yield 1;
yield 2;
} finally {
console.log('finally runs');
}
yield 3;
}
<p>const it = g();
it.next(); // {value: 1, done: false}
it.return('end'); // → {value: 'end', done: true},并输出 'finally runs'注意:finally 在 return() 被调用时执行,但 yield 3 永远不会执行。
立即学习“Java免费学习笔记(深入)”;
return() 和 return 语句的区别
生成器函数体内写 return value 是正常退出(等价于 yield 后隐式返回),而 it.return(value) 是外部强制终止:
- 函数内
return 42:仅在自然执行到该语句时生效,需走完前面所有逻辑 - 外部
it.return(42):立刻中断,无论当前停在哪(包括刚初始化未开始、或卡在某个yield)
实用场景示例
适合需要“取消”或“提前收尾”的情况,比如:
- 异步迭代中用户主动取消请求
- 资源清理(配合
finally或显式释放) - 测试中模拟生成器中途结束
例如:
function* fetchItems() {
yield 'connecting...';
yield 'fetching A';
yield 'fetching B';
yield 'done';
}
<p>const it = fetchItems();
console.log(it.next()); // {value: 'connecting...', done: false}
it.return('aborted'); // {value: 'aborted', done: true}
console.log(it.next()); // {value: undefined, done: true}


















