Generater遍历器对象生成函数

Generator 遍历器对象生成函数

形式上,Generator 函数是一个普通函数,但是有两个特征

  1. function关键字与函数名之间有一个星号,function与*的位置没有规定
  2. 函数体内部使用yield表达式,定义不同的内部状态
1
2
3
4
function* foo(x, y) { ··· } 
function * foo(x, y) { ··· }
function *foo(x, y) { ··· }
function*foo(x, y) { ··· }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function* helloWorldGenerator() {
yield 'hello';
yield 'world';
return 'ending';
}

var hw = helloWorldGenerator();

hw.next()
// { value: 'hello', done: false }
hw.next()
// { value: 'world', done: false }
hw.next()
// { value: 'ending', done: true }
hw.next()
// { value: undefined, done: true }

定义了一个 Generator 函数helloWorldGenerator,它内部有两个yield表达式(hello和world),即该函数有三个状态:hello,world 和 return 语句(结束执行)。

可以把generater函数理解成一个状态机,封装了多个内部状态

yield + next

Generator函数是分段执行的,yield语句是暂停执行的标记,而next方法可以恢复执行

调用 Generator函数,该函数并不执行,返回的也不是函数运行结果,而是会返回一个遍历器对象,是 Generator 函数的内部指针,调用next方法
可以依次遍历 Generator 函数内部的每一个状态。
Generator函数其实提供了一种可以暂停执行的函数。yield表达式就是暂停标志。

每次调用遍历器对象的next方法,就会返回一个有着value和done两个属性的对象。

  • value是当前的内部状态的值,是yield后面那个表达式的值
  • done属性是一个布尔值,表示是否遍历结束

yield + next 执行步骤

  1. 遇到yield表达式,就暂停执行后面的操作,并将紧跟在yield后面的那个表达式的值,作为返回的对象的value属性值。
  2. 下一次调用next方法时,从上一次yield表达式停下来的地方,再继续往下执行,直到遇到下一个yield表达式。
  3. 如果没有再遇到新的yield表达式,就一直运行到函数结束,直到return语句为止,并将return语句后面的表达式的值,作为返回的对象的value属性值
  4. 如果该函数没有return语句,则返回的对象的value属性值为undefined。

Generator 函数可以不用yield表达式,这时就变成了一个单纯的暂缓执行函数

1
2
3
4
5
6
7
8
9
setTimeout(function () {
let data = 'fr'
function* f() {
console.log(data)
}

var generator = f()
generator.next()
}, 2000)

yield表达式后面的表达式,只有当调用next方法、内部指针指向该语句时才会执行,因此等于为 JS提供了手动的惰性求值的语法功能

yield表达式只能用在 Generator 函数里面,用在其他地方都会报错。

yield表达式如果用在另一个表达式之中,必须放在圆括号里面。

1
2
3
4
5
6
7
function* demo() {
console.log('Hello' + yield); // SyntaxError
console.log('Hello' + yield 123); // SyntaxError

console.log('Hello' + (yield)); // OK
console.log('Hello' + (yield 123)); // OK
}

yield表达式用作函数参数或放在赋值表达式的右边,可以不加括号。

1
2
3
4
function* demo() {
foo(yield 'a', yield 'b'); // OK
let input = yield; // OK
}

next方法的参数

yield表达式本身没有返回值,或者说总是返回undefined。

next方法可以带一个参数,该参数就会被当作上一个yield表达式的返回值

由于next方法的参数表示上一个yield表达式的返回值,所以在第一次使用next方法时,传递参数是无效的。第一个next方法用来启动遍历器对象,所以不用带有参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function* foo(x) {
var y = 2 * (yield (x + 1));
var z = yield (y / 3);
return (x + y + z);
}

var a = foo(5);
a.next() // Object{value:6, done:false}
a.next() // Object{value:NaN, done:false}
a.next() // Object{value:NaN, done:true}

var b = foo(5);
b.next() // { value:6, done:false }
b.next(12) // { value:8, done:false }
b.next(13) // { value:42, done:true }
// x5 y24 z13

Generator.prototype.throw()

Generator 函数返回的遍历器对象,都有一个throw方法,可以在函数体外抛出错误,然后在 Generator 函数体内捕获

throw方法可以接受一个参数,该参数会被catch语句接收,建议抛出Error对象的实例。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var g = function* () {
try {
yield;
} catch (e) {
console.log('内部捕获', e);
}
};

var i = g();
i.next();

try {
i.throw('a');
i.throw('b');
} catch (e) {
console.log('外部捕获', e);
}
// 内部捕获 a
// 外部捕获 b

遍历器对象i连续抛出两个错误。第一个错误被 Generator 函数体内的catch语句捕获。i第二次抛出错误,由于 Generator 函数内部的catch语句已经执行过了,不会再捕捉到这个错误了,所以这个错误就被抛出了 Generator 函数体,被函数体外的catch语句捕获

Generator.prototype.return()

Generator 函数返回的遍历器对象,还有一个return方法,可以返回给定的值,并且终结遍历 Generator 函数。

如果return方法调用时,不提供参数,则返回值的value属性为undefined

1
2
3
4
5
6
7
8
9
10
11
function* gen() {
yield 1;
yield 2;
yield 3;
}

var g = gen();

g.next() // { value: 1, done: false }
g.return('foo') // { value: "foo", done: true }
g.next() // { value: undefined, done: true }

与iterater的关系

任意一个对象的Symbol.iterator方法,等于该对象的遍历器生成函数,调用该函数会返回该对象的一个遍历器对象

Generator 函数就是遍历器生成函数,因此可以把 Generator 赋值给对象的Symbol.iterator属性,从而使得该对象具有 Iterator 接口。

1
2
3
4
5
6
7
8
var myIterable = {};
myIterable[Symbol.iterator] = function* () {
yield 1;
yield 2;
yield 3;
};

[...myIterable] // [1, 2, 3]

Generator 函数执行后,返回一个遍历器对象。该对象本身也具有Symbol.iterator属性,执行后返回自身。

1
2
3
4
function* gen(){
}
var g = gen()
g[Symbol.iterator]() === g // true

for…of

for…of循环可以自动遍历 Generator 函数运行时生成的Iterator对象,且此时不再需要调用next方法。

一旦next方法的返回对象的done属性为true,for…of循环就会中止,且不包含该返回对象

1
2
3
4
5
6
7
8
9
10
11
function* foo() {
yield 1;
yield 2;
yield 3;
return 4;
}

for (let v of foo()) {
console.log(v);
}
// 1 2 3
  • for..of和generater实现斐波那契数列
1
2
3
4
5
6
7
8
9
10
11
function* fibonacci() {
let [prev, curr] = [0, 1];
for (;;) {
yield curr;
[prev, curr] = [curr, prev + curr];
}
}

for (let n of fibonacci()) {
console.log(n);
}

利用for…of循环,可以写出遍历任意对象(object)的方法。原生的JS象没有遍历接口,无法使用for…of循环,通过 Generator 函数为它加上这个接口,就可以用了。

  1. 将 Generator 函数返回的 Iterator 对象,作为参数
  2. 将 Generator 函数加到对象的Symbol.iterator属性
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    // 1
    function* objectEntries(obj) {
    let propKeys = Reflect.ownKeys(obj);

    for (let propKey of propKeys) {
    yield [propKey, obj[propKey]];
    }
    }
    function* objectEntries() {
    let propKeys = Object.keys(this);
    for (let propKey of propKeys) {
    yield [propKey, this[propKey]];
    }
    }

    let jane = { first: 'Jane', last: 'Doe' };
    for (let [key, value] of objectEntries(jane)) {
    console.log(`${key}: ${value}`);
    }
    // first: Jane
    // last: Doe

除了for…of循环以外,扩展运算符(…)、解构赋值和Array.from方法内部调用的,都是遍历器接口。这意味着,它们都可以将 Generator 函数返回的 Iterator 对象,作为参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
function* numbers () {
yield 1
yield 2
return 3
yield 4
}

// 扩展运算符
[...numbers()] // [1, 2]

// Array.from 方法
Array.from(numbers()) // [1, 2]

// 解构赋值
let [x, y] = numbers();
x // 1
y // 2

// for...of 循环
for (let n of numbers()) {
console.log(n)
}
// 1
// 2

yield* 表达式

yield* 用来在一个 Generator 函数里面执行另一个 Generator 函数

任何数据结构只要有 Iterator 接口,就可以被yield*遍历

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function* foo() {
yield 'a';
yield 'b';
}

function* bar() {
yield 'x';
yield* foo();
yield 'y';
}

for (let v of bar()){
console.log(v);
}

如果yield*后面跟着一个数组,由于数组原生支持遍历器,因此就会遍历数组成员。

1
2
3
4
5
function* gen(){
yield* ["a", "b", "c"];
}

gen().next() // { value:"a", done:false }

yield*命令可以很方便地取出嵌套数组的所有成员

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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);
}
// a
// b
// c
// d
// e

由于扩展运算符…默认调用 Iterator 接口,所以上面这个函数也可以用于嵌套数组的平铺

1
[...iterTree(tree)] // ["a", "b", "c", "d", "e"]

作为对象属性的 Generator 函数

1
2
3
4
5
let obj = {
* myGeneratorMethod() {
···
}
}

Generator 函数的this

Generator 函数也不能跟new命令一起用,会报错。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function* F() {
this.a = 1;
yield this.b = 2;
yield this.c = 3;
}
var obj = {};
var f = F.call(obj);

f.next(); // Object {value: 2, done: false}
f.next(); // Object {value: 3, done: false}
f.next(); // Object {value: undefined, done: true}

obj.a // 1
obj.b // 2
obj.c // 3

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function* F() {
this.a = 1;
yield this.b = 2;
yield this.c = 3;
}
var f = F.call(F.prototype);

f.next(); // Object {value: 2, done: false}
f.next(); // Object {value: 3, done: false}
f.next(); // Object {value: undefined, done: true}

f.a // 1
f.b // 2
f.c // 3

应用

1. 异步操作的同步化表达

Generator 函数的暂停执行的效果,意味着可以把异步操作写在yield表达式里面,等到调用next方法时再往后执行。这实际上等同于不需要写回调函数了,因为异步操作的后续操作可以放在yield表达式下面,反正要等到调用next方法时再执行。所以,Generator 函数的一个重要实际意义就是用来处理异步操作,改写回调函数

1
2
3
4
5
6
7
8
9
10
11
function* loadUI() {
showLoadingScreen();
yield loadUIDataAsynchronously();
hideLoadingScreen();
}
var loader = loadUI();
// 加载UI
loader.next()

// 卸载UI
loader.next()

Ajax 是典型的异步操作,通过 Generator 函数部署 Ajax 操作,可以用同步的方式表达。

1
2
3
4
5
6
7
8
9
10
11
12
13
function* main() {
var result = yield request("url")
console.log(result)
}

function request(url) {
makeAjaxCall(url, function(response){
it.next(response)
})
}

var it = main()
it.next()

2. 部署 Iterator 接口

利用 Generator 函数,可以在任意对象上部署 Iterator 接口。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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

3. 作为数据结构

Generator 可以看作是一个数组结构,因为 Generator 函数可以返回一系列的值,这意味着它可以对任意表达式,提供类似数组的接口。