JavaScript生成器中的收益率返回值的解析 [英] Resolution of yield return value in JavaScript generators

查看:121
本文介绍了JavaScript生成器中的收益率返回值的解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我为生成器上的next方法提供值,除了 yield关键字的右侧提供表达式之外,解决了吗?

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?

function* go() {
  console.log(yield 'a');
  console.log(yield 'b');
}

var g = go();
g.next();
g.next('one');
g.next('two');

输出:

one
two
Object {value: undefined, done: true}

根据输出,是提供给下一个方法的值,该值将用于yield右侧表达式返回的值.

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.

更新了代码以更好地反映我的问题.

code updated to better reflect my question.

推荐答案

根据输出,提供给下一个方法的值将用在yield右边的表达式返回的值上.

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.

提供给next方法的值未用于" yield右侧的值.提供给next 的值是 yield表达式最终求值的值.总是. yield右边的值是提供给生成器的消费者的值.

The value supplied to the next method is not "used over" the value to the right of yield. The value supplied to next is what the yield expression ultimately evaluates to. Always. The value to the right of the yield is what is supplied to the consumer of the generator.

这是生成器与消耗生成器的代码之间的双向通信.

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 }

这篇关于JavaScript生成器中的收益率返回值的解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆