← 中文资源

简体中文版本

生成器 finally 在 return 与 throw 时执行

生成器内部的 finally 在 return() 或 throw() 终止时执行,是所有关闭路径共用的清理钩子;return("done") 立即停机并把值带出,后续 next 只返回 done。

阅读英文原文

实现说明

在这里做循环的是 while (true)。

使用要点

  • 演示输出是带标签的(ticker cleanup after、tick 1:、tick 2:),每个操作都会留下自己的一行标注。

常见问题

除了语言工具链还要下载什么吗?

除了这个语言的工具链,什么都不用再下载。

核心语句

yield ++tick;

代码示例

function* ticker() {
  let tick = 0;
  try {
    while (true) {
      yield ++tick;
    }
  } finally {
    // finally runs on return() and throw() - not on plain next()
    console.log('ticker cleanup after', tick, 'ticks');
  }
}

const t = ticker();
console.log('tick 1:', t.next().value);
console.log('tick 2:', t.next().value);

// return() stops the generator immediately and carries the value out
console.log('stopped with:', t.return('done'));
console.log('done flag:', t.next().done);