我想弄清楚为什么 Generator.prototype.return
需要一个值。
我知道它会停止生成器处理并呈现每个 next
调用:
{
done: true,
value: undefined,
}
但是当您向它传递一个值,如 generator.return(4)
时,它所做的只是返回一个对象,就好像您调用了 Generator.prototype.next
而你的 value
属性是 4。
我唯一的猜测是,这在将生成器组合在一起或进行某种双向通信时可能很有用;虽然,因为它会关闭发电机,双向通信没有多大意义。
最佳答案
.return()
方法采用一个值,因为它以与 .next()
相同的方式提供双向通信。和 .throw()
做。
yield
表达式可以有 3 种不同的结果:
- 它可以像普通表达式一样计算结果值
- 它可以像
throw
语句那样求值,导致异常 - 它可以像
return
语句一样求值,导致在结束函数之前只求值finally
语句 - (第 4 种可能的结果是生成器永远不会恢复)
这是通过使用各自的值在挂起的生成器上调用各自的方法来实现的。这包括异常值和返回值。
But when you pass it a value such as
generator.return(4)
, all it does is give you back an object as if you calledGenerator.prototype.next
and your value prop was4
.
不一定。您可能会认为,当评估 return
语句时,它总是返回该返回值,并且与 throw
语句的异常不同,它无法被拦截。返回值确实不能在生成器函数内访问,但可以抑制或通过 finally
子句更改。
[ function* exampleA() {
try { yield; } finally {}
},
function* exampleB() {
try { yield; } finally { yield 'Y'; }
},
function* exampleC() {
try { yield; } finally { return 'Z'; }
},
function* exampleD() {
try { yield; } finally { throw 'E' }
}
].forEach(genFn => {
try {
const gen = genFn();
gen.next();
console.log(gen.return('X'));
} catch(e) {
console.log(e);
}
});
(当然,在 finally
子句中做这样的事情是一种不好的做法,但这是可能的)
关于javascript - 为什么 Generator.prototype.return 会取值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55179142/