8

我试图从 ES6 生成器函数的主体中抛出异常,但它没有通过。这是 ES6 规范的一部分还是 Babel 的怪癖?

这是我尝试过的代码(在 babeljs.io 上):

function *gen() {
    throw new Error('x');
}

try {
    gen();
    console.log('not throwing');
} catch(e) {
    console.log('throwing');
}

如果这确实是指定的 ES6 行为,那么发出异常信号的另一种方法是什么?

4

1 回答 1

10

您创建了一个迭代器,但没有运行它。

var g = gen();
g.next(); // throws 'x'

在 babel repl 上

这是另一个例子:

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);
}
于 2015-03-28T16:30:22.563 回答