1. 生成器函数声明
function* name(args){};
2. yield使用
1function* hello(){ 2 console.log('before hello'); //可看到hello()并不会立刻执行函数, 到第一次next调用时才会 3 var name = yield 'please input your name'; //将字符串传递给第一次next的结果, 并等待接收第二次next传过来的数据. 4 yield 'hello : ' + name; //返回结果给外部的next 5 console.log('after hello'); 6} 7 8var helloer = hello(); //返回生成器实例 9console.log(helloer.next()); //开始执行函数, 碰到第一个yield时返回 10console.log(helloer.next('haogrgr')); //接着第一个yield开始执行, 知道第二个yield, 这里通过next传递了参数. 11console.log(helloer.next()); //继续执行console.log('after hello');, 并返回done:true, 表示执行完了. 12 13//输出 14before hello 15Object {value: "please input your name", done: false} //第一次next调用输出到这里 16Object {value: "hello : haogrgr", done: false} //第二次next调用输出到这里 17after hello 18Object {value: undefined, done: true} //第三次next调用输出到这里
真实的执行顺序大概为:
11)创建generator实例. 2 32)第一次调用next方法, 开始执行函数体 4第一次 next{ 5 console.log('before hello'); 6 return 'please input your name'; //碰到yield, 返回yield后面的值 7} 8 93)next调用返回. 10 114)console输出next的返回值 Object {value: "please input your name", done: false} 12 135)第二次调用next方法, 并传入参数 'haogrgr'. 14第二次next{ 15 var name = 'haogrgr'; //haogrgr通过 next('haogrgr')传过来 16 return 'hello : ' + name; //碰到yield, 返回 17} 18 196)console输出next的返回值 Object {value: "hello : haogrgr", done: false} 20 217)第三次调用next 22第三次next{ 23 console.log('after hello'); 24} 25 268)console输出next的返回值 Object {value: undefined, done: true}
3. 总结
1)申明生成器函数使用 function* 开头.
2)调用生成器函数生成新的生成器实例.
3)第一次调用生成器next方法, 会开始执行函数, 直到碰到yield关键字.
4)yield关键字后面可以返回一个值给next调用.
5)同时, next方法可以有参数, 参数的值会作为 (yield exp) 的值.
6)yield和next可以看作是通过消息交流的两个组件, 比如 (yield msg) 传递一个消息给next, 然后暂停, 等待下个一个next调用传递一个值作为(yield msg)的返回值.
7)生成器函数中, return的值, 会作为最后一次next调用的返回值的value属性.
8)异常可以通过helloer.throw(err)来抛出.
4. 一种实现方式
1)转义, 比如facebook出的工具regenerator, 对于上面的例子, 会转换为如下的代码.
1var marked0$0 = [hello].map(regeneratorRuntime.mark); 2function hello() { 3 var name; 4 5 return regeneratorRuntime.wrap(function hello$(context$1$0) { 6 while (1) switch (context$1$0.prev = context$1$0.next) { 7 case 0: 8 console.log('before hello'); 9 context$1$0.next = 3; 10 return 'please input your name'; 11 case 3: 12 name = context$1$0.sent; 13 context$1$0.next = 6; 14 return 'hello : ' + name; 15 case 6: 16 console.log('after hello'); 17 case 7: 18 case "end": 19 return context$1$0.stop(); 20 } 21 }, marked0$0[0], this); 22} 23 24var helloer = hello(); 25console.log(helloer.next()); 26console.log(helloer.next('haogrgr')); 27console.log(helloer.next());
可以看到, 通过语法转换, 然后加上一个运行时, 成功了实现了生成器的功能.
通过将函数逻辑分割, 然后再上下文中记录当前的步骤, 来达到控制的转移(原本一路执行到底的函数变成了, 一节一节的跳来跳去的执行).
5. 参考资料
http://www.html5rocks.com/zh/tutorials/es6/promises/
http://www.infoq.com/cn/articles/es6-in-depth-generators
http://www.infoq.com/cn/articles/es6-in-depth-generators-continued
https://facebook.github.io/regenerator/
http://www.zhihu.com/question/30820791
http://swannodette.github.io/2013/08/24/es6-generators-and-csp/
http://swannodette.github.io/2013/07/31/extracting-processes/