Skip to content

生成器函数 ​

生成器(Generator)是可暂停和恢复执行的函数,且函数不一定会执行完。

基本语法 ​

生成器函数通过添加 * 来定义,并使用 yield 关键字进行流程控制,调用生成器函数会得到一个迭代器对象,不会执行函数体内的代码。

js
function *generator() {
  yield 1
  yield 2
  return 'end'
}

TIP

function* fn 和 function *fn 仅是代码风格上的区别。

yield 和 next() ​

yield 会标记暂停点,而 next() 方法会恢复函数执行,两者的配合就构成了一个双向消息传递系统,具体过程为:

  1. 首次调用 next() 会启动迭代器,执行函数体内的代码。
  2. 遇到第一个 yield 时暂停,返回 yield 表达式的值。
  3. 后续调用 next() 会从上一个暂停点恢复执行,执行到下一个 yield。
  4. 如此往复直到迭代器被消耗完。

yield 表达式的值会成为 next() 的返回值,而传给 next() 的参数会成暂停的 yield 的返回值,首次 next() 的参数会被忽略,因为没有对应的 yield 来接收。

js
function* generator() {
  const r1 = yield 1
  const r2 = yield r1 + 2
  const r3 = yield r2 * 3
  return r3 * r3
}  
const gen = generator()
console.log(gen.next())  // { value: 1, done: false }
console.log(gen.next(1)) // { value: 3, done: false }
console.log(gen.next(2)) // { value: 6, done: false }
console.log(gen.next(3)) // { value: 9, done: false }
console.log(gen.next(4)) // { value: undefined, done: true }

return ​

生成器内部使用 return 语句,用于提前结束生成器的执行。

  • 会立即结束函数执行,忽略后续的 yield,而 return 的值会成为 value 的值,done 将变为 true。
  • 若没有 return,则默认返回 { value: undefined, done: true }。
  • for...of 和扩展运算符会忽略 return 的值,因为 return 会使得生成器结束,即 done 会为 true,所以对应的 value 也会被忽略。

return() ​

在迭代器对象上调用 return() 方法,将从外部强制终止生成器。

  • 在生成器外部调用,强制结束生成器。
  • 该方法的参数将作为终止时返回的 value。
  • 若在第一个 next() 方法前调用则直接返回给定值,函数体完全不执行。
js
function *generator() {
  yield 'start'
  yield 'continue'
}
const gen = generator()
console.log(gen.next())        // { value: 'start', done: false }
console.log(gen.return('end')) // { value: 'end', done: true }
console.log(gen.next())        // { value: undefined, done: true }
  • 若有 try...finally,会执行 finally 代码块。
  • 若 finally 包含 yield,则 return() 方法返回的 done 会为 false,只有再次 next 后 done 才为 true。也就是会先执行 finally 里的代码,finally 块内的代码必须完整执行,而里面包含的 yield 会被视为常规暂停点。所以要么额外处理该情况,要么就避免在 finally 中使用 yield。
js
function *generator() {
  try {
    yield 'start'
    yield 'continue'
  } finally {
    yield 'finally'
  }
}
const gen = generator()
console.log(gen.next())        // { value: 'start', done: false }
console.log(gen.return('end')) // { value: 'finally', done: false }
console.log(gen.next())        // { value: 'end', done: true }

throw() ​

在迭代器对象上调用 throw() 方法,将从外部向生成器内部抛出错误。

  • 一般会抛出 Error 错误对象。
  • 会在当前暂停的 yield 表达式处抛出错误。
  • 若生成器内部有 try...catch 则错误可被捕获。
  • 若生成器内部无 try...catch 则后续 yield 不会执行,错误会传播到调用 throw() 方法的上下文。
  • 在生成器开始前或结束后调用 throw() 方法抛出错误,则会直接在外部抛出错误。
  • finally 块中抛出错误则会抛出到外部。
js
function* generator() {
  try {
    yield 1
    yield 2
  } catch (error) {
    yield `捕获:${error.message}`
  }
  yield 3
}
const gen = generator()
console.log(gen.next()) // { value: 1, done: false }
console.log(gen.throw(new Error('测试错误'))) // { value: '捕获:测试错误', done: false }
console.log(gen.next()) // { value: 3, done: false }