ES6产量* - 仅在参考发电机上一次产生一个值?

时间:2021-09-05 23:29:56

When having a generator reference another generator, is there a way to make it to where the referenced generator g1() will only iterate and yield one value at a time when yield* g1() is invoked? Instead of iterating through all values of g1() when yield* g1().

当一个生成器引用另一个生成器时,有没有办法使它到引用的生成器g1()只会迭代并在调用yield * g1()时产生一个值?而不是在yield * g1()时迭代g1()的所有值。

example from mozilla

来自mozilla的例子

For example.... instead of this:

例如....而不是这个:

function* g1() {
  yield 2;
  yield 3;
  yield 4;
}

function* g2() {
  yield 1;
  yield* g1();
  yield 5;
}

var iterator = g2();

console.log(iterator.next()); // { value: 1, done: false }
console.log(iterator.next()); // { value: 2, done: false }
console.log(iterator.next()); // { value: 3, done: false }
console.log(iterator.next()); // { value: 4, done: false }
console.log(iterator.next()); // { value: 5, done: false }

Make it do this:

这样做:

function* g1() {
  yield 2;
  yield 3;
  yield 4;
}

function* g2() {
  yield 1;
  yield* g1();
  //notice I am calling it a second time for value 3
  yield* g1();
  yield 5;
}

var iterator = g2();

console.log(iterator.next()); // { value: 1, done: false }
console.log(iterator.next()); // { value: 2, done: false }
console.log(iterator.next()); // { value: 3, done: false }
//notice value 4 is missing
console.log(iterator.next()); // { value: 5, done: false }

1 个解决方案

#1


2  

No. yield* delegates all the values yielded by the other generator.

No. yield *委托其他发电机产生的所有值。

If you want finer control, you should iterate it manually.

如果您想要更精细的控制,您应该手动迭代它。

function* g1() {
  yield 2;
  yield 3;
  yield 4;
}
function* g2() {
  yield 1;
  var it = g1();
  yield it.next().value;
  yield it.next().value;
  yield 5;
}

var iterator = g2();
console.log(iterator.next()); // { value: 1, done: false }
console.log(iterator.next()); // { value: 2, done: false }
console.log(iterator.next()); // { value: 3, done: false }
//notice value 4 is missing
console.log(iterator.next()); // { value: 5, done: false }

#1


2  

No. yield* delegates all the values yielded by the other generator.

No. yield *委托其他发电机产生的所有值。

If you want finer control, you should iterate it manually.

如果您想要更精细的控制,您应该手动迭代它。

function* g1() {
  yield 2;
  yield 3;
  yield 4;
}
function* g2() {
  yield 1;
  var it = g1();
  yield it.next().value;
  yield it.next().value;
  yield 5;
}

var iterator = g2();
console.log(iterator.next()); // { value: 1, done: false }
console.log(iterator.next()); // { value: 2, done: false }
console.log(iterator.next()); // { value: 3, done: false }
//notice value 4 is missing
console.log(iterator.next()); // { value: 5, done: false }