something wrong about generator

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

something wrong about generator

郑宇光
generator function shouldn't allow a "return value" when use yield or it need to return {value: {value: "end", done: true}, done: true} at the iter end when use yield*

code:

``` javascript
function* a() {
yield 1;
yield 2;
return "end"
}
//undefined
function* b() {
yield* a()
}
//undefined
c = b()
//b {<suspended>}
c.next()
//{value: 1, done: false}
c.next()
//{value: 2, done: false}
c.next()
//{value: undefined, done: true}
d = a()
//a {<suspended>}
d.next()
//{value: 1, done: false}
d.next()
//{value: 2, done: false}
d.next()
//{value: "end", done: true}
```

_______________________________________________
es-discuss mailing list
[hidden email]
https://mail.mozilla.org/listinfo/es-discuss
Reply | Threaded
Open this post in threaded view
|

Re: something wrong about generator

Vic99999
>or it need to return {value: {value: "end", done: true}, done: true}

this case is supported, seems, if to use:

function* b() {
        return yield* a()
}

_______________________________________________
es-discuss mailing list
[hidden email]
https://mail.mozilla.org/listinfo/es-discuss
Reply | Threaded
Open this post in threaded view
|

Re: something wrong about generator

Jeremy Martin
The `yield *` expression actually evaluates to the final value of the delegated generator (i.e., the final value when done is true).

In other words, if you modified your second generator in your example to the following:

    function* b() {
        const result = yield* a();
        console.log('THE RESULT', result);
    }

...you will see that `result` is equal to "end". So, to reiterate (pun not intended, but intentionally left intact), the final returned value of the delegated generator is not yielded from the parent generator, but is instead used as the value of the `yield *` expression itself.

Hope that helps!

On Sun, May 6, 2018 at 11:44 AM, Vic99999 <[hidden email]> wrote:
>or it need to return {value: {value: "end", done: true}, done: true}

this case is supported, seems, if to use:

function* b() {
        return yield* a()
}

_______________________________________________
es-discuss mailing list
[hidden email]
https://mail.mozilla.org/listinfo/es-discuss



--
Jeremy Martin
661.312.3853

_______________________________________________
es-discuss mailing list
[hidden email]
https://mail.mozilla.org/listinfo/es-discuss