GoingMyWay
GoingMyWay

Reputation: 17468

JavaScript, why the generator failed?

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.

Upvotes: 0

Views: 51

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386550

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; }

Upvotes: 0

Mμ.
Mμ.

Reputation: 8542

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.

Upvotes: 2

Related Questions