繁体   English   中英

为什么我的生成器没有产生从下一个方法传入的参数值?

[英]Why is my generator not yielding the argument value passed in from the next method?

我正在阅读MDN上有关生成器函数的文档以学习 redux-saga。 在这里他们提到您可以将参数传递给 iterator.next() 方法,如下面的网站上的示例所示。

function* logGenerator() {
  console.log(0);
  console.log(1, yield);
  console.log(2, yield);
  console.log(3, yield);
}

var gen = logGenerator();

// the first call of next executes from the start of the function
// until the first yield statement
gen.next();             // 0
gen.next('pretzel');    // 1 pretzel
gen.next('california'); // 2 california
gen.next('mayonnaise'); // 3 mayonnaise

这按预期工作。


现在我正在尝试使用它并编写了这个生成器。

 function* foo() { yield '1'; console.log(yield); yield '3'; return '4'; } var result = foo(); console.log(result.next()); console.log(result.next(2)); console.log(result.next()); console.log(result.next());

我期望的输出是1 2 3 4但我得到1,undefined,undefined,3,4 问题是什么 ?

编辑:正如评论中所指出的,我没有完全正确地显示输出。 请运行代码段。 如果我将参数添加到所有 next() 语句,我会得到以下输出。

{ value: '1', done: false }
{ value: undefined, done: false }
3
{ value: '3', done: false }
{ value: '4', done: true }

生成器函数使用yield在每个GeneratorObject.next() yield甚至会发生在console.log() ,所以应该会抛出一个语法错误。 当您第一次使用GeneratorObject.next()时,它产生了并且 Generator 停止执行,因此没有任何低于yield运行。 当您再次调用GeneratorObject.next(argument)时,就好像将参数传递给前一个yield ,仅在yield之前使用。 请参阅以下内容:

 function* gen_create(){ let a = yield 1; console.log(a); let b = yield 2; console.log(b); let c = yield 3; console.log(c); return 4; } const gen = gen_create(); console.log(gen.next('cool').value); // notice that 'cool' was not consoled console.log(gen.next().value); // nothing was passed so it's undefined console.log(gen.next('wow').value); console.log(gen.next('last return works like yield').value);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM