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
GoingMyWay
17.6k33 gold badges105 silver badges153 bronze badges
-
thats how generators work rightNaeem Shaikh– Naeem Shaikh2017年04月17日 09:32:47 +00:00Commented Apr 17, 2017 at 9:32
2 Answers 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
Mμ.
8,5723 gold badges28 silver badges36 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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
Nina Scholz
388k26 gold badges367 silver badges417 bronze badges
Comments
lang-js