类似 C# 的 IEmulator
定义
ES6 新增了 Generator ,类似于 C# 的 IEmulator 。
1 2 3 4 5 6 7 8 9 10 11 12
| function* gen() { yield 1 yield 2 yield 3 }
var g = gen()
console.log(g.next().value) console.log(g.next().value) console.log(g.next().value) console.log(g.next().value)
|
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) }
|
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) console.log(g.next().value) console.log(g.next().value) console.log(g.next().value) console.log(g.next().value) console.log(g.next().value)
|
Generator 可以模拟线程调度实现协程的效果,因为 Generator 可以让出控制权,达到暂停的效果。
Generator 也可以模拟 async 和 await 。
参考
MDN