我试图从ES6生成器函数的主体中抛出异常,但它没有通过。这是ES6规范的一部分还是Babel的怪癖?
以下是我尝试的代码(on babeljs.io):
function *gen() {
throw new Error('x');
}
try {
gen();
console.log('not throwing');
} catch(e) {
console.log('throwing');
}
如果确实指定了ES6行为,那么发出异常信号的替代方法是什么?
答案 0 :(得分:6)
您创建了一个迭代器,但没有运行它。
var g = gen();
g.next(); // throws 'x'
这是另一个例子:
function *gen() {
for (let i=0; i<10; i++) {
yield i;
if (i >= 5)
throw new Error('x');
}
}
try {
for (n of gen())
console.log(n); // will throw after `5`
console.log('not throwing');
} catch(e) {
console.log('throwing', e);
}