老师,不明白throw()后为什么还有一个打印输出
来源:2-57 Syntax(2)

程序媛_Lisa
2020-10-28
function * gen() {
let cnt = 0;
while (true) {
try {
yield console.log(cnt);
cnt++;
} catch(e) {
console.log(e.message);
}
}
}
let g = gen();
g.next();
g.next();
g.throw(new Error('暂停一下'));
/*
输出结果为:
0
1
暂停一下
1 // 不明白这里为什么多了一次打印输出
*/
写回答
1回答
-
慕粉1926294646
2020-11-06
因为 g.throw 让 catch 捕获到了,但是并未退出外层的 while 循环,直到遇到了 try 中的 yield 停了下来,所以是执行了 console.log(cnt),如果你在 catch 中的 console.log 后增加 break; 就不会有那个 1 了
00
相似问题