Javascript yield from the function nested inside generator

后端 未结 4 845
醉酒成梦
醉酒成梦 2021-01-03 23:55

This code generates an error:

function *giveNumbers() {
    [1, 2, 3].forEach(function(item) {
        yield item;
    })
}

This is probabl

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-04 00:34

    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;
    }
    

提交回复
热议问题