来自函数嵌套的Javascript生成器发生器 [英] Javascript yield from the function nested inside generator

查看:113
本文介绍了来自函数嵌套的Javascript生成器发生器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码产生错误:

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

这可能是因为yield不在生成器的函数内。有没有一个优雅的方式来克服这个?我的意思是:

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


推荐答案


这可能是因为yield不在生成器的函数内。

This is probably because yield is inside a function that is not a generator.

是的。您不能从回调中使用 yield

Yes. You cannot use yield from callbacks.


有没有一个优雅的方式来克服这个?

Is there an elegant way to overcome this?

取决于用例。通常没有理由要从回调中实际想要 yield

Depends on the use case. Usually there is zero reason to actually want to yield from a callback.

在你的情况下,你想要一个 for ... of 循环,在 .forEach q / 31344516/1048572>几乎每个方面反正:

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

这篇关于来自函数嵌套的Javascript生成器发生器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆