javascript - 为什么这个生成器会跳过 try block 之外的 yield?

标签 javascript ecmascript-6 generator

背景

我正在试验 Generator.prototype.throw() 的工作原理并做了这个例子:

var myGen = function *() {

    try{
        yield 1;
        yield 2;
        yield 3;
        yield 4;
        yield 5;
    }

    catch(err) {

        console.log(err);
    }

    yield 7;
    yield 8;
    yield 9;

}

var myIterator = myGen();

console.log(myIterator.next());
console.log(myIterator.next());
console.log(myIterator.next());

myIterator.throw(new Error('Bullocks!'));

console.log(myIterator.next());
console.log(myIterator.next());
console.log(myIterator.next());

在运行时会产生以下结果:

{ value: 1, done: false }
{ value: 2, done: false }
{ value: 3, done: false }
[Error: Bullocks!]
{ value: 8, done: false }
{ value: 9, done: false }
{ value: undefined, done: true }

问题

我可以理解 yield 4try block 的剩余部分在抛出错误后被跳过。

但是为什么生成器会跳过 yield 7

最佳答案

它不会跳过 yield 7。当您调用 throw() 时,控制流进入 catch block ,记录错误,然后继续执行直到下一个 yield 返回一个新的迭代器结果对象 { value: 7, done: false }

只是在您的代码中您没有 console.log 这个特定的结果对象。尝试:

console.log(myIterator.throw(new Error('Bullocks!')));

这在 step 11 and 13 of the spec 中有解释:

  1. Resume the suspended evaluation of genContext using abruptCompletion as the result of the operation that suspended it. Let result be the completion record returned by the resumed computation.
  2. (…)
  3. Return Completion(result).

关于javascript - 为什么这个生成器会跳过 try block 之外的 yield?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36857039/

相关文章:

javascript - Node require() 存在两个互相需要的脚本的问题

javascript - 无法使用jquery更改body,html位置: fixed to position: absolute

javascript - 我如何告诉 Workbox 检查新版本(页面加载后很久)

Javascript 扩展继承

python - python 的可变长度参数 (*args) 会在函数调用时扩展生成器吗?

Python 生成器和产量 : How to know which line the program is at

javascript - selenium IDE javascript 替换 : Throw an exception: missing ; before statement

javascript - 使用扩展运算符将对象插入数组?

java - grails,java-在message.properties中使用ECMAScript 6 Unicode代码点转义

python - 递归函数值生成器的多重处理