How does Generator.next() processes its parameter?

后端 未结 1 844
忘掉有多难
忘掉有多难 2021-02-08 03:04

The documentation says that \"You can also provide a parameter to the next method to send a value to the generator.\" Where does it sends it to?

For example, take these

1条回答
  •  逝去的感伤
    2021-02-08 03:41

    The key to understanding this is knowing how the next function retrieves the argument passed to next(), which is as the return value of the yield operator:

    [rv] = yield [expression];
    

    Independently of the value of [expression], yield will assign to rv the value passed to next().

    But, here comes the tricky part: yield will only assign the value passed to next() when resuming execution from a previous iteration. As a consequence, on the first iteration, yield does not assign anything to rv.

    For example, if I have this generator:

    function* gen() {
      // On the first iteration, yield does not return anything.
      //because it returns something ONLY when execution is resumed
      returnedFromYield = yield 'foo'; 
      yield returnedFromYield; 
    }
    

    returnedFromYield is undefined on the first iteration. When execution is resumed on the second iteration, yield assigns the passed value to the returnedFromYield variable, which is then returned:

    g.next(1); // 'foo'
    g.next(2); // 2
    

    Let's review another example:

    function* gen() {
      yield yield yield 5;
    }
    

    On the first iteration, (g.next()), yield will return 5, on the second iteration, (g.next(10)) yield is going to pass 10 to the second yield. That is, yield yield yield 5; on the second iteration is equivalent to yield yield 10;, and, on the third iteration, it's equivalent to yield valuePassedToNext.

    0 讨论(0)
提交回复
热议问题