Difference between yield and yield * operators in ECMAScript 6.0 "Harmony"?

7

I'm studying the use of generators in ECMAScript 6.0 "Harmony" .

I have already been able to understand its basic operation, such as declaration through the function* () { ... } syntax and the production of values through the yield operator.

However, I still can not find a satisfactory explanation for the operation of the yield* operator. In the generators page of the official language wiki , the following code, which would be equivalent to that operator, in terms of the yield operator:

let (g = <<expr>>) {
    let received = void 0, send = true, result = void 0;
    try {
        while (true) {
            let next = send ? g.send(received) : g.throw(received);
            try {
                received = yield next;
                send = true;
            } catch (e) {
                received = e;
                send = false;
            }
        }
    } catch (e) {
        if (!isStopIteration(e))
            throw e;
        result = e.value;
    } finally {
        try { g.close(); } catch (ignored) { }
    }
    result
}

I still could not clearly understand the purpose or effect of using this operator. Would anyone explain?

    
asked by anonymous 11.12.2013 / 20:01

1 answer

5

I'm still crawling on ES6, but as far as I understand yield* is required when you want to delegate yield to another generator. I found a simple example :

let delegatedIterator = (function* () {
  yield 'Hello!';
  yield 'Bye!';
}());

let delegatingIterator = (function* () {
  yield 'Greetings!';
  yield* delegatedIterator;
  yield 'Ok, bye.';
}());

// Prints "Greetings!", "Hello!", "Bye!", "Ok, bye."
for(let value of delegatingIterator) {
  console.log(value);
}

Notice that yield* delegatedIterator; consumes delegatedIterator completely. If you used yield delegatedIterator.next() , the output would be "Greetings!", "Hello!", "Ok, bye." .

Well, that's how I understood it, but as I said, I'm still not very sure about ES6. And I did not find a tool to test this ...

    
11.12.2013 / 20:29