Generator Function
异步执行、非阻塞式的设计,是 JavaScript 作为脚本语言,却能在 Node.js 运行时环境下保持高性能的关键,但在某些不苛求性能的场景下,也成为程序设计的一大障碍,层峦叠嶂的异步回调,很容易让你陷入所谓的 Callback Hell。借助 Generator Function 独特的 yield 构造,开发人员可以编写同步风格的 Node.js 程序,而不必在回调函数中层层嵌套。
Generator Function 是从 4.x 版本开始引入的,当时必须开启 --harmony
开关才能使用。
Generators And Iterators
对生成函数稍加深入分析,就会发现它和迭代器(Interator)是紧密关联的。
首先,什么是迭代器?
An object is an iterator when it knows how to access items from a collection one at a time, while keeping track of its current position within that sequence.
@cite https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators
一个对象如果定义了迭代行为,那么它就是可迭代的(Iterable),也就是说,它是一个迭代器。最简单的判断方法是,它可以由 for .. of
控制语句遍历。
由此,我们可以提出结论,Generator 的本质即迭代器,而 Generator Function 则是迭代器的生成器。
SEE
- ES6 generators in depth
http://www.2ality.com/2015/03/es6-generators.html
REF
- Iterators and generators
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators