Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generators in ES6: nested yields?

Can anyone explain to me how this code works? (nested yields):

function* anotherGenerator(i) {
  yield i + 1;
  yield i + 2;
  yield i + 3;
}

function* generator(i){
  yield i;
  yield* anotherGenerator(i);
  yield i + 10;
}

var gen = generator(10);

console.log(gen.next().value); // 10
console.log(gen.next().value); // 11
console.log(gen.next().value); // 12
console.log(gen.next().value); // 13
console.log(gen.next().value); // 20

At first console.log() we get a value of 10 , after that 11 ..12...13...20... how does this nested yield work?

like image 956
Keyur paralkar Avatar asked Aug 24 '26 16:08

Keyur paralkar


1 Answers

yield* anotherGenerator(i); is basically a convenient shorthand for

for (var value of anotherGenerator(i)) {
  yield value;
}
like image 64
Felix Kling Avatar answered Aug 27 '26 09:08

Felix Kling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!