JavaScript嵌套在函数生成器中
此代码会生成一个错误:
function *giveNumbers() { [1, 2, 3].forEach(function(item) { yield item; }) }
这可能是因为yield是在一个不是生成器的函数内。 有没有一个优雅的方法来克服这一点? 我的意思不是:
function *giveNumbers() { let list = [1, 2, 3]; for (let i = 0; i < list.length; i++) { yield list[i]; } }
这可能是因为yield是在一个不是生成器的函数内。
是。 你不能使用callbackyield
。
有没有一个优雅的方法来克服这一点?
取决于用例。 通常实际上想从callback中yield
原因是零的。
在你的情况下,你想要一个for…of
循环,这在任何方面都优于.forEach
:
function *giveNumbers() { for (let item of [1, 2, 3]) yield item; }
yield将结果返回给调用者。
让我们假设forEach
callback是一个生成器(在这里设置一个服装生成器不是问题) – 这意味着当callbackyield
结果时 – 它将返回forEach
。
基本上,在你的问题你试图做的是:
callback -> yields to forEach -> yields to giveNumbers -> yields to caller
所以,每个人都应该让结果回给giveNumbers
。 但是因为forEach
不能像这样工作,所以如果没有为forEach
服装重新制作原型arrays是不可能的。
其实,你的第二个片段是最优雅的开始。
你也可以使用while
和传递参数( Demo )
function *giveNumbers(array, start) { var index = start || 0; while(array.length > index + 1) { yield array[index++]; } return array[index]; } var g = giveNumbers([1,2,3], 0); var finished = false; while(!finished) { var next = g.next(); console.log(next.value); if(next.done) { finished = true; } }