0

I want to write a simple generator to get the increased value by call next

> var gg = next_id();
> function* next_id() {
 var current_id = 1;
 yield current_id;
 current_id ++;
 return current_id;
}
> gg.next()
Object {value: 1, done: false}
> gg.next()
Object {value: 2, done: true}
> gg.next()
Object {value: undefined, done: true}
> gg.next()
Object {value: undefined, done: true}

Why this generator just generate 2 value?

And I changed the code

function* next_id() {
 var current_id = 1;
 while (1) {
 yield current_id;
 current_id ++;
 }
 return current_id;
}

It works, it really made me confused.

asked Apr 17, 2017 at 9:29
1
  • thats how generators work right Commented Apr 17, 2017 at 9:32

2 Answers 2

2

Because you only call yield once. It looks like this is what you are trying to do:

function* next_id() {
 var index = 0;
 while(true)
 yield index++;
}
var gen = next_id();
console.log(gen.next()); 
console.log(gen.next()); 
console.log(gen.next());

Refer to the documentation of generators here.

answered Apr 17, 2017 at 9:34
Sign up to request clarification or add additional context in comments.

Comments

0

You need a loop and discard the return statement, which ends the function, whereas yield just stops the the execution of the generator.

In your edit, the return statement is never reached, because the loop runs forever.

function* next_id() {
 var current_id = 1;
 while (true) {
 yield current_id;
 current_id++;
 }
}
var gg = next_id();
console.log(gg.next()); // { value: 1, done: false }
console.log(gg.next()); // { value: 2, done: false }
console.log(gg.next()); // { value: 3, done: false }
console.log(gg.next()); // { value: 4, done: false }
.as-console-wrapper { max-height: 100% !important; top: 0; }

answered Apr 17, 2017 at 9:33

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.