Search code examples
javascriptgeneratorv8yield

With V8 JavaScript, is it possible that normal functions `yield` a value?


I know yield* can be used to compose generator, like this

 function* foo() {
      yield* bar();
      yield 1;
 }
 function* bar() {
      yield 2;
 }

But if I have some normal function yield a value.

  function xx()
  {
      yield 1;
  }

v8 says

  yield 1;
         ^
  SyntaxError: Unexpected number`

Does it mean that yield only saves the environment of a generator, not the full call stack and there is no way to stop and resume a normal function like generator?

I heard in FireFox(SpiderMonkey), yield can be used in normal function which is not compatible with ES6.


Solution

  • Yes, yield is only available in generators. Generators are marked by * in ES6, which wasn't the case in the earlier SpiderMonkey implementation predating the ES6 draft. That's why you could use yield in a "normal" function in SpiderMonkey -- which then would not be normal at all, but actually a generator.

    IOW, in either case, yield belongs to a generator. And it always produces a shallow, one-shot continuation (but you can delegate explicitly with yield*).