实现说明
在这里做循环的是 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);