背景
我正在试验 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 4
和 try
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 中有解释:
- 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.
- (…)
- Return Completion(result).
关于javascript - 为什么这个生成器会跳过 try block 之外的 yield?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36857039/