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
Joshua Engel
5135 silver badges19 bronze badges
1 Answer 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
Rodrigo5244
5,5752 gold badges29 silver badges39 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js
for (var x of foo()) { yield x; }. Spec: ecma-international.org/ecma-262/7.0/… . edit: Well, you have to callfoo()first to get the iterator.yield*expression is used to delegate to another generator or iterable object." developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…*