5

If I have a line like:

yield* foo()

Could I replace it with something to the tune of:

while(true) {
 var x = foo.next();
 if(x.done)
 break;
 yield x;
}

Clearly that's more verbose, but I'm trying to understand if yield* is merely syntactic sugar, or if there's some semantic aspect I'm unclear on.

asked Jan 6, 2017 at 17:50
4
  • 3
    Nope, it's pretty much that. Simpler: for (var x of foo()) { yield x; }. Spec: ecma-international.org/ecma-262/7.0/… . edit: Well, you have to call foo() first to get the iterator. Commented Jan 6, 2017 at 17:53
  • "The yield* expression is used to delegate to another generator or iterable object." developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…* Commented Jan 6, 2017 at 17:59
  • Thanks, @FelixKling. I feel myself developing cancer of the semicolon. Commented Jan 6, 2017 at 17:59
  • And thanks for the spec link, @FelixKling. The specification has some extra features for handling throws from iterables. And there's an oddity in that yield actually yields an IterResultObject that yield* does not.... plus something else about a type called "return". Commented Jan 6, 2017 at 18:30

1 Answer 1

1

Instead of yield x you need to do yield x.value. You also need to call foo to get the iterator. .next is a method of the iterator returned by the foo generator.

function *foo() {
 yield 1;
 yield 2;
 yield 3;
}
function *f() {
 yield *foo();
}
console.log(Array.from(f()));
function *g() {
 var iterator = foo();
 while (true) {
 var x = iterator.next();
 if (x.done) break;
 yield x.value;
 }
}
console.log(Array.from(g()));

answered Feb 6, 2017 at 0:15
Sign up to request clarification or add additional context in comments.

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.