This code generates an error:
function *giveNumbers() {
[1, 2, 3].forEach(function(item) {
yield item;
})
}
This is probably because yield is inside a function that is not a generator. Is there an elegant way to overcome this? I mean other than:
function *giveNumbers() {
let list = [1, 2, 3];
for (let i = 0; i < list.length; i++) {
yield list[i];
}
}
Yes. You cannot use
yield
from callbacks.Depends on the use case. Usually there is zero reason to actually want to
yield
from a callback.In your case, you want a
for…of
loop, which is superior to.forEach
in almost every aspect anyway:you can use the
yield *
syntax.You can also use
while
and pass arguments as such (Demo)yield returns the result to the caller.
let's assume the
forEach
callback is a generator (it's not a problem to set a costume generator there) - it means tha when the callbackyield
the result - it yields it back toforEach
.Basically, in your question what you attemp to do is:
So,
forEach
should yield the result back togiveNumbers
. but sinceforEach
doesn't work like this, it's impossible without re-prototype arrays with costumeforEach
.Actually, you second snippet is the most elegant to begin with.