4 ms·
> A generator isn't special, it is just a function returning an iterator. A generator should be able to return normally as well as yield. But in a generator fu
by ptx 12y ago
> A generator isn't special, it is just a function returning an iterator. A generator should be able to return normally as well as yield.
But in a generator function the iterator is returned immediately, before any of the code in the function runs, so how would it return anything else?
For example:
function* f() {
console.log("function commencing!");
for (x of [1, 2, 3]) {
console.log("yielding " + x);
yield x;
}
}
var it = f();
console.log("iterator returned from function:", it);
console.log(it.next().value);
would print:
"iterator returned from function:" Generator { } Scratchpad/1:19
"function commencing!" Scratchpad/1:11
"yielding 1" Scratchpad/1:13
1
So even if the very first thing the function does is
if (isTuesday())
return something;
else
yield somethingElse;
...by that point it would have already returned an iterator, so it would be too late to decide otherwise, wouldn't it?
- TazeTSchnitzel 12y ago>But in a generator function the iterator is returned immediately, before any of the code in the function runs, so how would it return anything else? Oh, that's interesting, I didn't know ES6 implemented generators that way. That's really weird. EDIT: Looks like PHP does the same thing. Hmm, I can see the merits of an asterisk, then.
- ptx 12y agoPython works the same way, so I just assumed ES6 did as well and tested it in Firefox. :)