[英]Resolution of yield return value in JavaScript generators
If I supply a value to the next
method on a generator, in addition to supplying an expression to the right of the yield
keyword, how is the return value of the yield
resolved? 如果我将值提供给生成器上的
next
方法, 除了在yield
关键字的右边提供一个表达式之外 ,如何解决yield
的返回值?
function* go() {
console.log(yield 'a');
console.log(yield 'b');
}
var g = go();
g.next();
g.next('one');
g.next('two');
Output: 输出:
one
two
Object {value: undefined, done: true}
In light of the output, it is the value supplied to the next method that is used over the value returned by the expression to the right of yield
. 根据输出,提供给下一个方法的值将在
yield
右边的表达式返回的值上使用。
Edit: code updated to better reflect my question. 编辑:更新代码以更好地反映我的问题。
There are two ways to interpret "return value of the yield". 有两种方法可以解释“收益率的返回值”。
You could mean the value of the expression yield 'a'
. 您可能会说表达式
yield 'a'
的值。 That has the value one
, as you can see from your output. 从输出中可以看到,其值为
one
。
Or you could mean the value passed to yield
, which is effectively "returned" from the generator's next
method. 或者,您可能意味着传递给
yield
的值实际上是从生成器的next
方法“返回”的。 Your code snippet doesn't really reveal this. 您的代码片段并未真正揭示这一点。 Try:
尝试:
console.log('next1', g.next());
console.log('next2', g.next('one'));
console.log('next3', g.next('two'));
That way you can see the values coming out of the generator, which should look something like: 这样一来,您可以看到生成器发出的值,看起来应该像这样:
"next1", {value: "a", done: false}
"next2", {value: "b", done: false}
"next3", {value: undefined, done: true}
One other thing you can do is add an ordinary return
value at the end of your generator function, and that will be the value
for next3
. 您可以做的另一件事是在生成器函数的末尾添加一个普通的
return
值,该值将成为next3
的value
。
In light of the output, it is the value supplied to the next method that is used over the value returned by the expression to the right of yield.
根据输出,提供给下一个方法的值将在yield右边的表达式返回的值上使用。
The value supplied to the next
method is not "used over" the value to the right of yield
. 提供给
next
方法的值不会“超出” yield
右边的值。 The value supplied to next
is what the yield
expression ultimately evaluates to. 提供给
next
的值是 yield
表达式最终求值的值。 Always. 总是。 The value to the right of the
yield
is what is supplied to the consumer of the generator. yield
右边的值是提供给发电机使用者的yield
。
It is a two-way communication between the generator and the code consuming the generator. 生成器与消耗生成器的代码之间是双向通信。
function* go() {
console.log(yield 'a'); // 'one'
console.log(yield 'b'); // 'two'
}
var g = go();
console.log(g.next()); // { value: 'a', done: false }
console.log(g.next('one')); // { value: 'b', done: false }
console.log(g.next('two')); // { value: undefined, done: true }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.