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];
}
}
This is probably because yield is inside a function that is not a generator.
Yes. You cannot use yield
from callbacks.
Is there an elegant way to overcome this?
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:
function *giveNumbers() {
for (let item of [1, 2, 3])
yield item;
}
you can use the yield *
syntax.
function *giveNumbers() {
yield * [1, 2, 3].map(function(item) {
return item;
})
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With