类似 C# 的 IEmulator

定义

ES6 新增了 Generator ,类似于 C# 的 IEmulator 。

1
2
3
4
5
6
7
8
9
10
11
12
function* gen() {  // 函数前面加 * 表示是 generator 函数
yield 1 // yield 返回一个值
yield 2
yield 3
}

var g = gen()

console.log(g.next().value) // 1
console.log(g.next().value) // 2
console.log(g.next().value) // 3
console.log(g.next().value) // undefine

Generator 可以是无限的

1
2
3
4
5
6
7
8
9
10
11
function* Fibonacci() {
"use strict"
let a = 0
let b = 1
while(true){
yield a
let sum = a + b
a = b
b = sum
}
}

打印前十个斐波那契数

1
2
3
4
5
var f = Fibonacci();
for(var i = 0; i < 10; i++){
console.log(f.next().value)
}
// 0 1 1 2 3 5 8 13 21 54

Generator 可以嵌套

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

function* AnotherGen(){
yield "a"
yield "b"
yield "c"
}

var g = gen()

console.log(g.next().value) // 1
console.log(g.next().value) // "a"
console.log(g.next().value) // "b"
console.log(g.next().value) // "c"
console.log(g.next().value) // 2
console.log(g.next().value) // 3

Generator 可以模拟线程调度实现协程的效果,因为 Generator 可以让出控制权,达到暂停的效果。

Generator 也可以模拟 async 和 await 。

参考

MDN