目录

🍏 ES6 Generator 相关

  • 怎么理解 ES6 中的 Generator
  • Generator 的使用场景?

# 理解

ES6 中的 Generator 函数是一种异步编程的解决方案,语法行为与传统的函数不相同。

此前,解决异步编程的手段有:回调函数和 Promise。

执行 Generator 函数会返回一个遍历器对象,可以依次遍历 Generator 函数内部的每一个状态。形式上,Generator 函数是一个普通函数,但是有两个特征: function 关键词与 Generator 函数名称之间有一个星号 * ;函数体内部使用 yield 表达式,定义不同的内部状态。

🌰 例子:

function* myGenerator() {
  yield 'hello'
  yield 'world'
}
1
2
3
4

# 使用场景

Generator 函数会返回一个遍历器对象,即具有 Symbol.iterator (可迭代)属性,并且返回自身。

🌰 例子:

function* gen {
  // ...
}

var g = gen()
g[Symol.iterator]() === g // true
1
2
3
4
5
6

通过 yield 关键字可以暂停 Generator 函数返回的遍历器对象的状态。

🌰 例子:

function* myGenerator() {
  yield 'hello'
  yield 'world'
  yield 'generator'
}
1
2
3
4
5

这个例子中的 Generator 函数存在三个状态,分别是 helloworldgenerator

通过 next 方法可以遍历到下一个内部状态。其运行逻辑为:

  • 遇到 yield 表达式就会暂停执行后面的操作,并将紧跟 yield 后面的那个表达式的值,作为返回的对象的 value 属性值。
  • 下一次调用 next 方法时,再继续往下执行,知道遇到下一个 yield 表达式。
  • 如果没有再遇到新的 yield 表达式,就一直运行到函数结束,直到 return 语句为止,并且将 return 语句后面的表达式的值作为返回的对象的 value 属性值。
  • 如果该函数没有 return 表达式,则返回的对象的 value 属性值为 undefined
var mg = myGenerator()

mg.next() // { value: 'hello', done: false }
mg.next() // { value: 'world', done: false }
mg.next() // { value: 'generator', done: true }
mg.next() // { value: undefined, done: true }
1
2
3
4
5
6

value 对应状态值, done 表示下个状态是否存在(存在为 falsetrue 为不存在)。 yield 表达式本身没有返回值,总是返回 undefined

🌰 完整例子:

function* foo(x) {
 	let y = 2 * (yield (x + 1))
  let z = yield (y / 3)
  return (x + y + z)
}

let a = foo(5)
a.next() // Object{value:6, done:false}
a.next() // Object{null, done:false}
a.next() // Object{null, 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 }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
📢 上次更新: 2022/09/02, 10:18:16