1. 生成器函数声明
function* name(args){};
2. yield使用
function* hello(){ console.log('before hello'); //可看到hello()并不会立刻执行函数, 到第一次next调用时才会 var name = yield 'please input your name'; //将字符串传递给第一次next的结果, 并等待接收第二次next传过来的数据. yield 'hello : ' + name; //返回结果给外部的next console.log('after hello'); } var helloer = hello(); //返回生成器实例 console.log(helloer.next()); //开始执行函数, 碰到第一个yield时返回 console.log(helloer.next('haogrgr')); //接着第一个yield开始执行, 知道第二个yield, 这里通过next传递了参数. console.log(helloer.next()); //继续执行console.log('after hello');, 并返回done:true, 表示执行完了. //输出 before hello Object {value: "please input your name", done: false} //第一次next调用输出到这里 Object {value: "hello : haogrgr", done: false} //第二次next调用输出到这里 after hello Object {value: undefined, done: true} //第三次next调用输出到这里
真实的执行顺序大概为:
1)创建generator实例. 2)第一次调用next方法, 开始执行函数体 第一次 next{ console.log('before hello'); return 'please input your name'; //碰到yield, 返回yield后面的值 } 3)next调用返回. 4)console输出next的返回值 Object {value: "please input your name", done: false} 5)第二次调用next方法, 并传入参数 'haogrgr'. 第二次next{ var name = 'haogrgr'; //haogrgr通过 next('haogrgr')传过来 return 'hello : ' + name; //碰到yield, 返回 } 6)console输出next的返回值 Object {value: "hello : haogrgr", done: false} 7)第三次调用next 第三次next{ console.log('after hello'); } 8)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, 对于上面的例子, 会转换为如下的代码.
var marked0$0 = [hello].map(regeneratorRuntime.mark); function hello() { var name; return regeneratorRuntime.wrap(function hello$(context$1$0) { while (1) switch (context$1$0.prev = context$1$0.next) { case 0: console.log('before hello'); context$1$0.next = 3; return 'please input your name'; case 3: name = context$1$0.sent; context$1$0.next = 6; return 'hello : ' + name; case 6: console.log('after hello'); case 7: case "end": return context$1$0.stop(); } }, marked0$0[0], this); } var helloer = hello(); console.log(helloer.next()); console.log(helloer.next('haogrgr')); console.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/