Generator(生成器)
- Generator function 是ES2015中非常重要的部分,提供了一种异步编程解决方案;
- Generator function 可以使用yield语句定义不同的内部状态,可以多次返回值;
- 书写方式如下:
function* G(x) {
let a = yield (x + 1);
let b = yield (a * a);
return (a + b);
}
let g = G(2); //返回一个指向内部状态的指针对象,即遍利器对象;
g.next(); // {value: 3, done: false}
g.next(4); // a = 4; {value: 16, done: false}
g.next(5); // a = 4; b = 5; {value: 9, done: true}
g.next(1); // {value: undefined, done: true}
注:由于next()方法的参数表示上一条yield语句的返回值,所以第一次调用.next()方法时,不能带参数;
- 应用
- 异步操作的同步表达式
- 控制流管理
- 部署Iterator接口
- 作为数据结构