繁体   English   中英

如何理解javascript生成器?

[英]How to understand javascript Generator?

我有一段代码

 function* dataConsumer() { console.log('Started'); console.log(`1. ${yield}`); console.log(`2. ${yield}`); return 'result'; } let genObj = dataConsumer(); genObj.next(); 

并且运行结果是

Started

我不明白为什么第二个console.log无法输出任何内容。 感谢帮助。

生成器构建在迭代器的顶部。 要了解生成器,首先需要了解迭代器。 请参阅文档

对于一个流,它运行到更接近的yield并终止函数调用。 在你再次打电话next ,它将从它终止的地方继续并再次工作直到最接近的yield ,当没有yields或它到达return语句时,它就完成了它的调用。

 function* dataConsumer() { console.log('Started'); console.log(`1. ${yield}`); // First `next` terminates before yield. Second `next` passes the value and terminates before the next yield. console.log(`2. ${yield}`); // Third call continues from the `yield` part and finishes the function, because we have returned return 'result'; } let genObj = dataConsumer(); genObj.next(); genObj.next('yield1'); genObj.next('yield2'); 

您还可以将参数传递给next函数,该函数将放在yield语句中。 此外, next函数返回一个关于生成器状态的对象,其属性value done 如果函数调用未完成,则返回done为false,最后您可以看到它设置为true

 function* dataConsumer() { console.log('Started'); const x = yield; console.log(`1. ${x}`); console.log(`2. ${yield}`); return 'result'; } let genObj = dataConsumer(); let result = genObj.next(); console.log(result); result = genObj.next('x is yield1'); console.log(result); result = genObj.next('yield2'); console.log(result); genObj.next(); // This one has nothing to do 

由于您可以在每个步骤中将参数传递给生成器,因此您也可以从中返回值。 你需要写一些类似的东西来return something ,只需用yield替换return

 function* dataConsumer() { yield 1; yield 2; yield 3; } let genObj = dataConsumer(); let result = genObj.next(); console.log(result); result = genObj.next(); console.log(result); result = genObj.next(); console.log(result); result = genObj.next(); console.log(result); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM