Es6 generators simple example won't work

Es6 generators simple example won't work
0

#1

Hi everyone!!
I am studying about es6 generators and have a question:
In the following example:

function* gen() { yield ‘test1’; yield ‘test2’; yield ‘test3’; }

const res1 = gen();

Everytime I do gen().next(); I always get Object {value: “test1”, done: false} (which is wrong,the generator should move on). Whereas if I call it like res1.next() (which is EXACTLY the same thing, since res1=gen()) it runs correctly until the end. Why is this happening? Have I misunderstood something?

Thank you in advance :slight_smile:


#2

Your gen fuction returns a Generator object, so calling gen() recreates the generator every time. It’s actually equivalent to:

const GeneratorFunction = Object.getPrototypeOf(function*(){}).constructor;
const g = new GeneratorFunction("yield 'test1'; yield 'test2'; yield 'test3';");
const iterator = g();

iterator.next();  // Object { value: "test1", done: false }
iterator.next();  // Object { value: "test2", done: false }
iterator.next();  // Object { value: "test3", done: false }
iterator.next();  // Object { value: undefined, done: true }

#3

Hi Velenir and thank you for your answer!!

So in your example variable g corresponds to my function gen right?
This means that everytime we call a genarator function it returns a new generator object.

Thanks a lot!