Question

I am writing the simple function of generator

function simpleGenerator(){
  yield "first";
  yield "second";
  yield "third";
};
var g = simpleGenerator();
console.log(g.next());

it is giving for the line of yield --

SyntaxError: missing ; before statement

i am unable to get the reason for showing error... if i use return like

function simpleGenerator(x){
 while(true){
  var a=x*2;
  return a;
 }
}
var g = simpleGenerator(2);
console.log(g);

It is working properly,

Was it helpful?

Solution

Generator functions have to be defined like this

function * simpleGenerator() {    # Note the `*` after `function` keyword
    yield "first";
    yield "second";
    yield "third";
};
var g = simpleGenerator();
console.log(g.next());
# { value: 'first', done: false }

Quoting from the ECMA 6's Harmony page for Generator functions,

The function syntax is extended to add an optional * token:

FunctionDeclaration:
    "function" "*"? Identifier "(" FormalParameterList? ")" "{" FunctionBody "}"   FunctionExpression:
    "function" "*"? Identifier? "(" FormalParameterList? ")" "{" FunctionBody "}"

A function with a * token is known as a generator function. The following two unary operators are only allowed in the immediate body of a generator function (i.e., in the body but not nested inside another function):

AssignmentExpression:
    ...
    YieldExpression

YieldExpression:
    "yield" ("*"? AssignmentExpression)?

An early error is raised if a yield or yield* expression occurs in a non-generator function.YieldExpression:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top