Generator函数详解
1、简介
1.1、基本概念
Generator函数是ES6提供的一种异步编程解决方案,语法行为与传统函数完全不同。
对于Generator函数有多种理解角度。从语法上,首先可以把它理解成一个状态机,封装了多个内部状态。
执行Generator函数会返回一个遍历器对象。也就是说,Generator函数除了是状态机,还是一个遍历器对象生成函数。返回的遍历器对象,可以依次遍历Generator函数内部的每一个状态。形式上,Generator函数是一个普通函数,但是有两个特征:
- 一是function命令与函数名之间有一个星号;
- 二是函数体内部使用yield语句定义不同的内部状态("yield"在英语里的意思就是"产出")。
js
function* helloWorldGenerator() {
yield 'hello';
yield 'world';
return 'ending';
}
let hw = helloWorldGenerator();
console.log(hw.next());//{ value: 'hello', done: false }
上面的代码定义了一个Generator函数------helloWorldGenerator,它内部有两个yield语句"hello"和"world",即该函数有3个状态:hello、world和return语句(结束执行)。
Generator函数的调用方法与普通函数一样,也是在函数名后面加上一对圆括号。不同的是,调用Generator函数后,该函数并不执行,返回的也不是函数运行结果,而是一个指向内部状态的指针对象,也就是上一章介绍的遍历器对象(Iterator Object)。
下一步,必须调用遍历器对象的next方法,使得指针移向下一个状态。也就是说,每次调用next方法,内部指针就从函数头部或上一次停下来的地方开始执行,直到遇到下一条yield语句(或return语句)为止。换言之,Generator函数是分段执行的,yield语句是暂停执行的标记,而next方法可以恢复执行。
js
let hw = helloWorldGenerator();
console.log(hw.next());//{ value: 'hello', done: false }
console.log(hw.next());//{ value: 'world', done: false }
console.log(hw.next());//{ value: 'ending', done: true }
console.log(hw.next());//{ value: undefined, done: true }
第1次调用,Generator函数开始执行,直到遇到第一条yield语句为止。next方法返回一个对象,它的value属性就是当前yield语句的值hello,done属性的值false表示遍历还没有结束。第2次调用,Generator函数从上次yield语句停下的地方,一直执行到下一条yield语句。next方法返回的对象的value属性就是当前yield语句的值world,done属性的值false表示遍历还没有结束。
第3次调用,Generator函数从上次yield语句停下的地方,一直执行到return语句(如果没有return语句,就执行到函数结束)。next方法返回的对象的value属性就是紧跟在return语句后面的表达式的值(如果没有return语句,则value属性的值为undefined),done属性的值true表示遍历已经结束。
第4次调用,此时Generator函数已经运行完毕,next方法返回的对象的value属性为undefined,done属性为true。以后再调用next方法,返回的都是这个值。
总结一下,调用Generator函数,返回一个遍历器对象,代表Generator函数的内部指针。以后,每次调用遍历器对象的next方法,就会返回一个有着value和done两个属性的对象。value属性表示当前的内部状态的值,是yield语句后面那个表达式的值;done属性是一个布尔值,表示是否遍历结束。
ES6没有规定function关键字与函数名之间的星号写在哪个位置。这导致下面的写法都能通过。
js
function * foo(x, y) {}
function *foo(x, y) {}
function* foo(x, y) {}
function*foo(x, y) {}
由于Generator函数仍然是普通函数,所以一般的写法是上面的第3种,即星号紧跟在function关键字后面。本书中也采用这种写法。
1.2、yield语句
由于Generator函数返回的遍历器对象只有调用next方法才会遍历下一个内部状态,所以其实提供了一种可以暂停执行的函数。yield语句就是暂停标志。
遍历器对象的next方法的运行逻辑如下。
- 遇到yield语句就暂停执行后面的操作,并将紧跟在yield后的表达式的值作为返回的对象的value属性值。
- 下一次调用next方法时再继续往下执行,直到遇到下一条yield语句。
- 如果没有再遇到新的yield语句,就一直运行到函数结束,直到return语句为止,并将return语句后面的表达式的值作为返回的对象的value属性值。
- 如果该函数没有return语句,则返回的对象的value属性值为undefined。
需要注意的是,yield语句后面的表达式,只有当调用next方法、内部指针指向该语句时才会执行,因此等于为JavaScript提供了手动的"惰性求值"(Lazy Evaluation)的语法功能。
js
function* gen() {
yield 123 + 456;
}
上面的代码中,yield后面的表达式123+456不会立即求值,只会在next方法将指针移到这一句时才求值。
yield语句与return语句既有相似之处,又有区别。相似之处在于都能返回紧跟在语句后的表达式的值。区别在于每次遇到yield函数暂停执行,下一次会从该位置继续向后执行,而return语句不具备位置记忆的功能。一个函数里面只能执行一次(或者说一条)return语句,但是可以执行多次(或者说多条)yield语句。正常函数只能返回一个值,因为只能执行一次return语句;Generator函数可以返回一系列的值,因为可以有任意多条yield语句。从另一个角度看,也可以说Generator生成了一系列的值,这也就是其名称的来历(在英语中,"generator"这个词是"生成器"的意思)。
Generator函数可以不用yield语句,这时就变成了一个单纯的暂缓执行函数。
js
function* f() {
console.log('执行了');
}
let generator = f();
setTimeout(function() {
generator.next();
}, 2000);
上面的代码中,函数f如果是普通函数,在为变量generator赋值时就会执行。但是函数f是一个Generator函数,于是就变成只有调用next方法时才会执行。
另外需要注意,yield语句不能用在普通函数中,否则会报错。
js
(function(){
yield 1;
})()//Error
上面的代码在一个普通函数中使用yield语句,结果产生一个句法错误。
下面是另外一个例子。
js
let arr = [1, [[2, 3], 4], [5, 6]];
let flat = function* (a) {
a.forEach(function(item){
if(typeof item !== 'number') {
yield* flat(item);
} else {
yield item;
}
})
};
for(let f of flat(arr)) {
console.log(f);
}
上面的代码也会产生句法错误,因为forEach方法的参数是一个普通函数,但是在里面使用了yield语句。一种修改方法是改用for循环。
js
let arr = [1, [[2, 3], 4], [5, 6]];
let flat = function* (a) {
let length = a.length;
for(let i = 0; i < length; i++) {
let item = a[i];
if(typeof item !== 'number') {
yield* flat(item);
} else {
yield item;
}
}
};
for(let f of flat(arr)) {
console.log(f);
}
// 1
// 2
// 3
// 4
// 5
// 6
另外,yield语句如果用在一个表达式中,必须放在圆括号里面。
js
console.log('Hello' + yield);//Error
console.log('Hello' + yield 123);//Error
console.log('Hello' + (yield));//OK
console.log('Hello' + (yield 123));//OK
yield语句用作函数参数或用于赋值表达式的右边,可以不加括号。
js
foo(yield 'a', yield 'b');//OK
let input = yield;//OK
1.3、与Iterator接口的关系
上一章说过,任意一个对象的Symbol.iterator方法等于该对象的遍历器对象生成函数,调用该函数会返回该对象的一个遍历器对象。
遍历器对象本身也有Symbol.iterator方法,执行后返回自身。
js
function* gen() {
//...
}
let g = gen();
console.log(g[Symbol.iterator]() === g);//true
上面的代码中,gen是一个Generator函数,调用它会生成一个遍历器对象g。它的Symbol.iterator属性也是一个遍历器对象生成函数,执行后返回它自己。
上面的代码中,gen是一个Generator函数,调用它会生成一个遍历器对象g。它的Symbol.iterator属性也是一个遍历器对象生成函数,执行后返回它自己。
2、next方法的参数
yield语句本身没有返回值,或者说总是返回undefined。next方法可以带一个参数,该参数会被当作上一条yield语句的返回值。
js
function* f() {
for(let i = 0; true; i++) {
let reset = yield i;
if(reset) {
i = -1;
}
}
}
let g = f();
console.log(g.next());//{ value: 0, done: false }
console.log(g.next());//{ value: 1, done: false }
console.log(g.next());//{ value: 2, done: false }
上面的代码先定义了一个可以无限运行的Generator函数f,如果next方法没有参数,每次运行到yield语句,变量reset的值总是undefined。当next方法带一个参数true时,当前的变量reset就被重置为这个参数(即true),因而i会等于-1,下一轮循环就从-1开始递增。这个功能有很重要的语法意义。Generator函数从暂停状态到恢复运行,其上下文状态(context)是不变的。通过next方法的参数就有办法在Generator函数开始运行后继续向函数体内部注入值。也就是说,可以在Generator函数运行的不同阶段,从外部向内部注入不同的值,从而调整函数行为。
js
function* foo(x) {
let y = 2 * (yield (x + 1));
let z = yield (y / 3);
return (x + y + z);
}
let a = foo(5);
console.log(a.next());//{ value: 6, done: false }
console.log(a.next());//{ value: NaN, done: false }
console.log(a.next());//{ value: NaN, done: true }
上面的代码中,第二次运行next方法的时候不带参数,导致y的值等于2 * undefined(即NaN),除以3以后还是NaN,因此返回对象的value属性也等于NaN。第三次运行Next方法的时候不带参数,所以z等于undefined,返回对象的value属性等于5+NaN+undefined,即NaN。
如果向next方法提供参数,返回结果就完全不一样了。上面的代码第一次调用b的next方法时,返回x+1的值6;第二次调用next方法,将上一次yield语句的值设为12,因此y等于24,返回y/3的值8;第三次调用next方法,将上一次yield语句的值设为13,因此z等于13,这时x等于5,y等于24,所以return语句的值等于42。
注意,由于next方法的参数表示上一条yield语句的返回值,所以第一次使用next方法时不能带有参数。V8引擎直接忽略第一次使用next方法时的参数,只有从第二次使用next方法开始参数才是有效的。从语义上讲,第一个next方法用来启动遍历器对象,所以不用带有参数。如果想要第一次调用next方法时就能够输入值,可以在Generator函数外面再包一层。
js
function wrapper(generatorFunction) {
return function(...args) {
let generatorObject = generatorFunction(...args);
generatorObject.next();
return generatorObject;
}
}
const wrapped = wrapper(function* () {
console.log(`First input: ${yield}`);
return `DONE`;
})
wrapped().next('hello');//First input: hello
上面的代码中,Generator函数如果不用wrapper先包一层,是无法第一次调用next方法就输入参数的。
再看一个通过next方法的参数向Generator函数内部输入值的例子。
js
function* dataConsumer() {
console.log('Started');
console.log(`1. ${yield}`);
console.log(`2. ${yield}`);
return 'result';
}
let genObj = dataConsumer();
genObj.next();//Started
genObj.next('a');//1. a
genObj.next('b');//2. b
上面的代码是一个很直观的例子,每次通过next方法向Generator函数输入值,然后打印出来。
3、for...of循环
for...of循环可以自动遍历Generator函数,且此时不再需要调用next方法。
js
function* foo() {
yield 1;
yield 2;
yield 3;
yield 4;
yield 5;
yield 6;
}
for(let v of foo()) {
console.log(v);
}
// 1
// 2
// 3
// 4
// 5
// 6
上面的代码使用for...of循环依次显示5条yield语句的值。这里需要注意,一旦next方法的返回对象的done属性为true,for...of循环就会终止,且不包含该返回对象,所以上面的return语句返回的6不包括在for...of循环中。
下面是一个利用Generator函数和for...of循环实现斐波那契数列的例子。
js
function* fibonacci() {
let [prev, curr] = [0, 1];
for(;;) {
[prev, curr] = [curr, prev + curr];
yield curr;
}
}
for(let n of fibonacci()) {
if(n > 1000)
break;
console.log(n);
}
由上可见,使用for...of语句时不需要使用next方法。
for...of循环、扩展运算符(...)、解构赋值和Array.from方法内部调用的都是遍历器接口。这意味着,它们可以将Generator函数返回的Iterator对象作为参数。
js
function* numbers() {
yield 1
yield 2
return 3
yield 4
}
console.log([...numbers()]);//[ 1, 2 ]
Array.from(numbers());//[1, 2]
let [x, y] = numbers();//x=1, y=2
for (let n of numbers()) {
console.log(n);
}
// 1
// 2
利用for...of循环可以写出遍历任意对象的方法。原生的JavaScript对象没有遍历接口,无法使用for...of循环,通过Generator函数为它加上这个接口就可以用了。
js
function* objectEntries(obj) {
let propKeys = Reflect.ownKeys(obj);
for(let propKey of propKeys) {
yield [propKey, obj[propKey]];
}
}
let jane = {first: 'Jane', last: 'Doe'};
for(let [key, value] of objectEntries(jane)) {
console.log(`${key}: ${value}`);
}
// first: Jane
// last: Doe
上面的代码中,对象jane原生不具备Iterator接口,无法用for...of遍历。我们通过Generator函数objectEntries为它加上遍历器接口,就可以用for...of遍历了。加上遍历器接口的另一种写法是,将Generator函数加到对象的Symbol.iterator属性上。
js
function* objectEntries() {
let propKeys = Object.keys(this);
for(let propKey of propKeys) {
yield [propKey, this[propKey]];
}
}
let jane = {first: 'Jane', last: 'Doe'};
jane[Symbol.iterator] = objectEntries;
for(let [key, value] of jane) {
console.log(`${key}: ${value}`);
}
// first: Jane
// last: Doe
4、Generator.prototype.throw()
Generator函数返回的遍历器对象都有一个throw方法,可以在函数体外抛出错误,然后在Generator函数体内捕获。
js
let g = function* () {
while(true) {
try {
yield;
} catch (e) {
if (e != 'a')
throw e;
console.log('内部捕获', e);
}
}
};
let i = g();
i.next();
try {
i.throw('a');
i.throw('b');
} catch(e) {
console.log('外部捕获', e);
}
// 内部捕获 a
// 外部捕获 b
上面的代码中,遍历器对象i连续抛出两个错误。第一个错误被Generator函数体内的catch语句捕获,然后Generator函数执行完成,于是第二个错误被函数体外的catch语句捕获。
注意,不要混淆遍历器对象的throw方法和全局的throw命令。上面的错误是用遍历器对象的throw方法抛出的,而不是用throw命令抛出的。后者只能被函数体外的catch语句捕获。
js
let g = function* () {
while(true) {
try {
yield;
} catch (e) {
if (e != 'a')
throw e;
console.log('内部捕获', e);
}
}
};
let i = g();
i.next();
try {
throw new Error('a');
throw new Error('b');
} catch(e) {
console.log('外部捕获', e);
}
// 外部捕获 Error: a
上面的代码之所以只捕获了a,是因为函数体外的catch语句块捕获了抛出的a错误后,就不会再执行try语句块了。
如果Generator函数内部没有部署try...catch代码块,那么throw方法抛出的错误将被外部try...catch代码块捕获。
js
let g = function* () {
while(true) {
yield;
console.log('内部捕获', e);
}
};
let i = g();
i.next();
try {
i.throw('a');
i.throw('b');
} catch(e) {
console.log('外部捕获', e);
}
// 外部捕获 a
上面的代码中,遍历器函数g内部没有部署try...catch代码块,所以抛出的错误直接被外部catch代码块捕获。
如果Generator函数内部部署了try...catch代码块,那么遍历器的throw方法抛出的错误不影响下一次遍历,否则遍历直接终止。
js
let gen = function* gen() {
yield console.log('hello');
yield console.log('world');
}
let g = gen();
g.next();
try {
g.throw();
} catch(e) {
g.next();
}
//hello
上面的代码只输出hello就结束了,因为第二次调用next方法时遍历器状态已经变成终止了。但如果使用throw命令抛出错误,则不会影响遍历器状态。
js
let gen = function* gen() {
yield console.log('hello');
yield console.log('world');
}
let g = gen();
g.next();
try {
throw new Error();
} catch(e) {
g.next();
}
// hello
// world
上面的代码中,throw命令抛出的错误不会影响到遍历器的状态,所以两次执行next方法都完成了正确的操作。
这种函数体内捕获错误的机制大大方便了对错误的处理。如果使用回调函数的写法,想要捕获多个错误,就不得不为每个函数写一个错误处理语句。
js
foo('a', function(a){
if(a.error) {
throw new Error(a.error);
}
foo('b', function(b) {
if(b.error) {
throw new Error(b.error);
}
foo('c', function(c) {
if(c.error) {
throw new Error(c.error);
}
console.log(a, b, c);
})
})
})
使用Generator函数可以大大简化上面的代码。
js
function* g() {
try {
let a = yield foo('a');
let b = yield foo('b');
let c = yield foo('c');
} catch (e) {
console.log(e);
}
console.log(e);
}
反过来,Generator函数内抛出的错误也可以被函数体外的catch捕获。
js
function* foo() {
let x = yield 3;
let y = x.toUpperCase();
yield y;
}
let it = foo();
console.log(it.next());//{ value: 3, done: false }
try {
console.log(it.next(42));//TypeError: x.toUpperCase is not a function
} catch(err) {
console.log(err);
}
上面的代码中,第二个next方法向函数体内传入一个参数42,数值是没有toUpperCase方法的,所以会抛出一个TypeError错误,被函数体外的catch捕获。
一旦Generator执行过程中抛出错误,就不会再执行下去了。如果此后还调用next方法,将返回一个value属性等于undefined、done属性等于true的对象,即JavaScript引擎认为这个Generator已经运行结束。
js
function* g() {
yield 1;
console.log('throwing an exception');
throw new Error('generator broke!');
yield 2;
yield 3;
}
function log(generator) {
let v;
console.log('starting generator');
try {
v = generator.next();
console.log('第一次运行next方法', v);
} catch(err) {
console.log('捕获错误', v);
}
try {
v = generator.next();
console.log('第二次运行next方法', v);
} catch(err) {
console.log('捕获错误', v);
}
try {
v = generator.next();
console.log('第三次运行next方法', v);
} catch(err) {
console.log('捕获错误', v);
}
}
log(g());
// starting generator
// 第一次运行next方法 { value: 1, done: false }
// throwing an exception
// 捕获错误 { value: 1, done: false }
// 第三次运行next方法 { value: undefined, done: true }
上面的代码一共3次运行next方法,第2次运行时会抛出错误,然后第3次运行时Generator函数就已结束,不再执行下去。
5、Generator.prototype.return()
Generator函数返回的遍历器对象还有一个return方法,可以返回给定的值,并终结Generator函数的遍历。
js
function* gen() {
yield 1;
yield 2;
yield 3;
}
let g = gen();
console.log(g.next());//{ value: 1, done: false }
console.log(g.return('foo'));//{ value: 'foo', done: true }
console.log(g.next());//{ value: undefined, done: true }
上面的代码中,遍历器对象g调用return方法后,返回值的value属性就是return方法的参数foo。同时,Generator函数的遍历终止,返回值的done属性为true,以后再调用next方法,done属性总是返回true。
如果return方法调用时不提供参数,则返回值的vaule属性为undefined。
js
function* gen() {
yield 1;
yield 2;
yield 3;
}
let g = gen();
console.log(g.next());//{ value: 1, done: false }
console.log(g.return());//{ value: undefined, done: true }
如果Generator函数内部有try...finally代码块,那么return方法会推迟到finally代码块执行完再执行。
js
function* numbers() {
yield 1;
try {
yield 2;
yield 3;
} finally {
yield 4;
yield 5;
}
yield 6;
}
let g = numbers();
console.log(g.next());//{ value: 1, done: false }
console.log(g.next());//{ value: 2, done: false }
console.log(g.return(7));//{ value: 4, done: false }
console.log(g.next());//{ value: 5, done: false }
console.log(g.next());//{ value: 7, done: true }
上面的代码中,调用return方法后就开始执行finally代码块,然后等到finally代码块执行完再执行return方法。
6、yield*语句
如果在Generator函数内部调用另一个Generator函数,默认情况下是没有效果的。
js
function* foo() {
yield 'a';
yield 'b';
}
function* bar() {
yield 'x';
foo();
yield 'y';
}
for(let v of bar()) {
console.log(v);
}
// x
// y
上面的代码中,foo和bar都是Generator函数,在bar里面调用foo是不会有效果的。
这时就需要用到yield*语句,用来在一个Generator函数里面执行另一个Generator函数。
js
function* foo() {
yield 'a';
yield 'b';
}
function* bar() {
yield 'x';
yield* foo();
yield 'y';
}
//等同于
// function* bar() {
// yield 'x';
// yield 'a';
// yield 'b';
// yield 'y';
// }
//等同于
// function* bar() {
// yield 'x';
// for(let v of foo()) {
// console.log(v);
// }
// yield 'y';
// }
for(let v of bar()) {
console.log(v);
}
// x
// a
// b
// y
再来看一个对比的例子。
js
function* inner() {
yield 'hello!';
}
function* outer1() {
yield 'open';
yield inner();
yield 'close';
}
let gen = outer1();
console.log(gen.next().value);//open
console.log(gen.next().value);//Object [Generator] {}
console.log(gen.next().value);//close
function* outer2() {
yield 'open';
yield* inner();
yield 'close';
}
let gen = outer2();
console.log(gen.next().value);//open
console.log(gen.next().value);//hello!
console.log(gen.next().value);//close
上面的例子中,outer2使用了yield*,outer1没有使用。结果就是outer1返回一个遍历器对象,outer2返回该遍历器对象的内部值。
从语法角度看,如果yield命令后面跟的是一个遍历器对象,那么需要在yield命令后面加上星号,表明返回的是一个遍历器对象。这被称为yield*语句。
js
let delegatedIterator = (function* () {
yield 'Hello!';
yield 'Bye!';
}());
let delegatingIterator = (function* () {
yield 'Greetings!';
yield* delegatedIterator;
yield 'Ok, bye.';
}());
for(let value of delegatingIterator) {
console.log(value);
}
// Greetings!
// Hello!
// Bye!
// Ok, bye.
上面的代码中,delegatingIterator是代理者,delegatedIterator是被代理者。由于yield*delegatedIterator语句得到的值是一个遍历器,所以要用星号表示。运行结果就是使用一个遍历器遍历了多个Generator函数,有递归的效果。
yield*语句等同于在Generator函数内部部署一个for...of循环。
js
function* concat(iter1, iter2) {
yield* iter1;
yield* iter2;
}
//等同于
function* concat(iter1, iter2) {
for(let value of iter1) {
yield value;
}
for (let value of iter2) {
yield value;
}
}
上面的代码说明,yield*不过是for...of的一种简写形式,完全可以由后者替代。
如果yield*后面跟着一个数组,由于数组原生支持遍历器,因此会遍历数组成员。
js
function* gen() {
yield* ['a', 'b', 'c'];
}
console.log(gen().next());//{ value: 'a', done: false }
上面的代码中,yield命令后面如果不加星号,返回的是整个数组,加了星号就表示返回数组的遍历器对象。
实际上,任何数据结构只要有Iterator接口,就可以用yield*遍历。
js
let read = (function* () {
yield 'hello';
yield* 'hello';
}());
console.log(read.next().value);//hello
console.log(read.next().value);//h
上面的代码中,yield语句返回整个字符串,yield*语句返回单个字符。因为字符串具有Iterator接口,所以用yield*遍历。
如果被代理的Generator函数有return语句,那么可以向代理它的Generator函数返回数据。
js
function* foo() {
yield 2;
yield 3;
return 'foo';
}
function* bar() {
yield 1;
let v = yield *foo();
console.log('v:' + v);
yield 4;
}
let it = bar();
console.log(it.next());//{ value: 1, done: false }
console.log(it.next());//{ value: 2, done: false }
console.log(it.next());//{ value: 3, done: false }
console.log(it.next());
// v:foo
// { value: 4, done: false }
console.log(it.next());//{ value: undefined, done: true }
在上面的代码第4次调用next方法时,屏幕上会有输出,这是因为函数foo的return语句向函数bar提供了返回值。
再看一个例子。
js
function* genFuncWithReturn() {
yield 'a';
yield 'b';
return 'The result';
}
function* logReturned(genObj) {
let result = yield* genObj;
console.log(result);
}
console.log([...logReturned(genFuncWithReturn())]);
// The result
// [ 'a', 'b' ]
上面的代码中,存在两次遍历。第一次是扩展运算符遍历函数logReturned返回的遍历器对象,第二次是yield*语句遍历函数genFuncWithReturn返回的遍历器对象。这两次遍历的效果是叠加的,最终表现为扩展运算符遍历函数genFuncWithReturn返回的遍历器对象。所以,最后的数据表达式得到的值等于[ˈaˈ,ˈbˈ]。但是,函数genFuncWithReturn的return语句的返回值The result会返回给函数logReturned内部的result变量,因此会有终端输出。
yield*命令可以很方便地取出嵌套数组的所有成员。
js
function* iterTree(tree) {
if(Array.isArray(tree)) {
for(let i = 0; i < tree.length; i++) {
yield* iterTree(tree[i]);
}
} else {
yield tree;
}
}
const tree = ['a', ['b', 'c'], ['d', 'e']];
for(let x of iterTree(tree)) {
console.log(x);
}
下面是一个稍微复杂的例子,使用yield*语句遍历完全二叉树。
js
//二叉树构造,3个参数分别是左子树、当前节点和右子树
function Tree(left, label, right) {
this.left = left;
this.label = label;
this.right = right;
}
//下面是中序(inorder)遍历函数。
//由于返回的是一个遍历器,所以要用Generator函数。
//函数体内采用递归算法,所以左子树和右子树要用yield*遍历。
function* inorder(t) {
if(t) {
yield* inorder(t.left);
yield t.label;
yield* inorder(t.right);
}
}
//生成二叉树
function make(array) {
//判断是否为叶子节点
if(array.length == 1)
return new Tree(null, array[0], null);
return new Tree(make(array[0]), array[1], make(array[2]));
}
let tree = make([[['a'], 'b', ['c']], 'd', [['e'], 'f', ['g']]]);
//遍历二叉树
let result = [];
for (let node of inorder(tree)) {
result.push(node);
}
console.log(result);
// [
// 'a', 'b', 'c',
// 'd', 'e', 'f',
// 'g'
// ]
7、作为对象属性的Generator函数
如果一个对象的属性是Generator函数,那么可以简写成下面的形式。
js
let obj = {
* myGeneratorMethod() {
...
}
};
上面的代码中,myGeneratorMethod属性前面有一个星号,表示这个属性是一个Generator函数。
其完整形式如下,与上面的写法是等价的。
js
let obj = {
myGeneratorMethod: function* () {
//...
}
}
8、Generator函数的this
Generator函数总是返回一个遍历器,ES6规定这个遍历器是Generator函数的实例,它也继承了Generator函数的prototype对象上的方法。
js
function* g() {}
g.prototype.hello = function() {
return 'hi';
};
let obj = g();
console.log(obj instanceof g);//true
console.log(obj.hello());//hi
上面的代码表明,Generator函数g返回的遍历器obj是g的实例,而且继承了g.prototype。但是,如果把g当作普通的构造函数,则并不会生效,因为g返回的总是遍历器对象,而不是this对象。
js
function* g() {
this.a = 11;
}
let obj = g();
console.log(obj.a);//undefined
上面的代码中,Generator函数g在this对象上添加了一个属性a,但是obj对象拿不到这个属性。
js
function* F() {
yield this.x = 2;
yield this.y = 3;
}
上面的代码中,函数F是一个构造函数,又是一个Generator函数。这时,使用new命令就无法生成F的实例了,因为F返回的是一个内部指针。
js
'next' in (new F())
//true
上面的代码中,由于new F()返回的是一个Iterator对象,具有next方法,所以上面的表达式值为true。
如果要把Generator函数当作正常的构造函数使用,可以采用下面的变通方法。首先生成一个空对象,使用bind方法绑定Generator函数内部的this。这样,构造函数调用以后,这个空对象就是Generator函数的实例对象了。
js
function* F() {
yield this.x = 2;
yield this.x = 3;
}
let obj = {};
let f = F.bind(obj)();
console.log(f.next());//{ value: 2, done: false }
console.log(f.next());//{ value: 3, done: false }
console.log(f.next());//{ value: undefined, done: true }
上面的代码中,首先是F内部的this对象绑定obj对象,然后调用它,返回一个Iterator对象。这个对象执行了3次next方法(因为F内部有2条yield语句),完成F内部所有代码的运行。这时,所有内部属性都绑定在obj对象上,因而obj对象也就成了F的实例。
9、含义
9.1、Generator与状态机
Generator是实现状态机的最佳结构。比如,下面的clock函数就是一个状态机。
js
let ticking = true;
let clock = function() {
if(ticking)
console.log('Tick!');
else
console.log('Tock!');
ticking = !ticking;
}
上面的clock函数一共有两种状态(Tick和Tock),每运行一次,就改变一次状态。这个函数如果用Generator实现,则如下。
js
let clock = function* (_) {
while(true) {
yield _;
console.log('Tick!');
yield _;
console.log('Tock!');
}
}
对比上面的Generator实现与ES5实现,可以看到少了用来保存状态的外部变量ticking,这样就更简洁,更安全(状态不会被非法篡改),更符合函数式编程的思想,在写法上也更优雅。Generator之所以可以不用外部变量保存状态,是因为它本身就包含了一个状态信息,即目前是否处于暂停态。
9.2、Generator与协程
协程(coroutine)是一种程序运行的方式,可以理解成"协作的线程"或"协作的函数"。协程既可以用单线程实现,也可以用多线程实现;前者是一种特殊的子例程,后者是一种特殊的线程。
协程与子例程的差异:
传统的"子例程"(subroutine)采用堆栈式"后进先出"的执行方式,只有当调用的子函数完全执行完毕,才会结束执行父函数。协程与其不同,多个线程(单线程情况下即多个函数)可以并行执行,但只有一个线程(或函数)处于正在运行的状态,其他线程(或函数)都处于暂停态(suspended),线程(或函数)之间可以交换执行权。也就是说,一个线程(或函数)执行到一半,可以暂停执行,将执行权交给另一个线程(或函数),等到稍后收回执行权时再恢复执行。这种可以并行执行、交换执行权的线程(或函数),就称为协程。
从实现上看,在内存中子例程只使用一个栈(stack),而协程是同时存在多个栈,但只有一个栈是在运行态。也就是说,协程是以多占用内存为代价实现多任务的并行运行。
协程与普通线程的差异:
不难看出,协程适用于多任务运行的环境。在这个意义上,它与普通的线程很相似,都有自己的执行上下文,可以分享全局变量。它们的不同之处在于,同一时间可以有多个线程处于运行态,但是运行的协程只能有一个,其他协程都处于暂停态。此外,普通的线程是抢占式的,到底哪个线程优先得到资源,必须由运行环境决定,但是协程是合作式的,执行权由协程自己分配。ECMAScript是单线程语言,只能保持一个调用栈。引入协程以后,每个任务可以保持自己的调用栈。这样做的最大好处,就是抛出错误时可以找到原始的调用栈,不至于像异步操作的回调函数那样,一旦出错原始的调用栈早已结束。
Generator函数是ES6对协程的实现,但属于不完全实现。Generator函数被称为"半协程"(semi-coroutine),意思是只有Generator函数的调用者才能将程序的执行权还给Generator函数。如果是完全实现的协程,任何函数都可以让暂停的协程继续执行。
如果将Generator函数当作协程,完全可以将多个需要互相协作的任务写成Generator函数,它们之间使用yield语句交换控制权。
10、应用
Generator可以暂停函数执行,返回任意表达式的值。这种特点使得Generator有多种应用场景。
10.1、异步操作的同步化表达
Generator函数的暂停执行效果,意味着可以把异步操作写在yield语句里面,等到调用next方法时再往后执行。这实际上等同于不需要写回调函数了,因为异步操作的后续操作可以放在yield语句下面,反正要等到调用next方法时再执行。所以,Generator函数的一个重要实际意义就是用于处理异步操作,改写回调函数。
js
function* loadUI() {
showLoadingScreen();
yield loadUIDataAsynchronously();
hideLoadingScreen();
}
let loader = loadUI();
//加载UI
loader.next();
//卸载UI
loader.next();
上面的代码表示,第一次调用loadUI函数时,该函数不会执行,仅返回一个遍历器。下一次对该遍历器调用next方法,则会显示加载界面,并且异步加载数据。等到数据加载完成,再一次使用next方法,则会隐藏加载界面。可以看到,这种写法的好处是所有加载界面的逻辑都被封装在一个函数中,按部就班非常清晰。
AJAX是典型的异步操作,通过Generator函数部署AJAX操作,可以用同步的方式表达。
js
function* main() {
let result = yield request('http://some.url');
let resp = JSON.parse(result);
console.log(resp.value);
}
function request(url) {
makeAjaxCall(url, function(response) {
ImageTrack.next(response);
});
}
let it = main();
it.next();
上面的main函数就是通过AJAX操作获取数据。可以看到,除了多了一个yield,它几乎与同步操作的写法完全一样。注意,makeAjaxCall函数中的next方法必须加上response参数,因为yield语句构成的表达式本身是没有值的,总是等于undefined。
下面是另一个例子,通过Generator函数逐行读取文本文件。
js
function* numbers() {
let file = new FileReader('numbers.txt');
try {
while(!file.eof) {
yield parseInt(file.readLine(), 10);
}
} finally {
file.close();
}
}
上面的代码打开文本文件,使用yield语句可以手动逐行读取文件。
10.2、控制流管理
如果有一个多步操作非常耗时,采用回调函数可能会写成下面这样。
js
step1(function(value1){
step2(value1, function(value2){
step3(value2, function(value3) {
step4(value3, function(value4) {
//do something with value4
})
})
})
})
采用Promise改写上面的代码如下。
js
Q.fcall(step1)
.then(step2)
.then(step3)
.then(step4)
.then(function (value4) {
//do something with value4
}, function (error) {
//Handle any error from step1 through step4
})
.done();
上面的代码已经把回调函数改成了直线执行的形式,但是加入了大量Promise的语法。
Generator函数可以进一步改善代码运行流程。
js
function* longRunningTask() {
try {
let value1 = yield step1();
let value2 = yield step2(value1);
let value3 = yield step3(value2);
let value4 = yield step4(value3);
//do something with value4
} catch(e) {
//Handle any error from step1 through step4
}
}
然后,使用一个函数按次序自动执行所有步骤。
js
scheduler(longRunningTask());
function scheduler(task) {
setTimeout(function() {
let taskObj = task.next(task.value);
//如果Generator函数未结束,就继续调用
if(!taskObj.done) {
task.value = taskObj.value;
scheduler(task):
}
}, 0);
}
注意,yield语句是同步运行,不是异步运行(否则就失去了取代回调函数的设计目的了)。
实际操作中,一般让yield语句返回Promise对象。
js
let Q = require('q');
function delay(milliseconds) {
let deferred = Q.defer();
setTimeout(deferred.resolve, milliseconds);
return deferred.promise;
}
function* f() {
yield delay(100);
}
上面的代码使用了Promise的函数库Q,yield语句返回的就是一个Promise对象。
多个任务按顺序一个接一个执行时,yield语句可以按顺序排列。多个任务需要并列执行时(比如只有A任务和B任务都执行完,才能执行C任务),可以采用数组的写法。
js
function* parallelDownloads() {
let [text1, text2] = yield [
taskA(),
taskB()
];
console.log(text1, text2);
}
上面的代码中,yield语句的参数是一个数组,成员就是两个任务------taskA和taskB,只有等这两个任务都完成,才会接着执行下面的语句。
10.3、部署Iterator接口
利用Generator函数可以在任意对象上部署Iterator接口。
js
function* iterEntries(obj) {
let keys = Object.keys(obj);
for(let i = 0; i < keys.length; i++) {
let key = keys[i];
yield [key, obj[key]];
}
}
let myObj = {foo: 3, bar: 7};
for(let [key, value] of iterEntries(myObj)) {
console.log(key, value);
}
// foo 3
// bar 7
上述代码中,myObj是一个普通对象,通过iterEntries函数就有了Iterator接口。也就是说,可以在任意对象上部署next方法。
下面是一个对数组部署Iterator接口的例子,尽管数组原生具有这个接口。
js
function* makeSimpleFenerator(array) {
let nextIndex = 0;
while(nextIndex < array.length) {
yield array[nextIndex++];
}
}
let gen = makeSimpleFenerator(['yo', 'ya']);
console.log(gen.next().value);//yo
console.log(gen.next().value);//ya
console.log(gen.next().value);//undefined
10.4、作为数据结构
Generator可以看作数据结构,更确切地说,可以看作一个数组结构,因为Generator函数可以返回一系列的值,这意味着它可以对任意表达式提供类似数组的接口。
js
function* doStuff() {
yield fs.readFile.bind(null, 'hello.txt');
yield fs.readFile.bind(null, 'world.txt');
yield fs.readFile.bind(null, 'and-such.txt');
}
上面的代码依次返回3个函数,但是由于使用了Generator函数,导致可以像处理数组那样处理这3个返回的函数。
js
for (task of doStuff()) {
//task是一个函数,可以像回调函数那样使用它
}
实际上,如果用ES5表达,完全可以用数组模拟Generator的这种用法。
js
function doStuff() {
return [
fs.readFile.bind(null, 'hello.txt'),
fs.readFile.bind(null, 'world.txt'),
fs.readFile.bind(null, 'and-such.text')
];
}
上面的函数可以用一模一样的for...of循环处理!两相比较不难看出,Generator使得数据或操作具备了类似数组的接口。