yield

yield 关键字用来暂停和恢复一个生成器函数((function*遗留的生成器函数)。

语法

[rv] = yield [expression];
expression
定义通过 迭代器协议从生成器函数返回的值。如果省略,则返回 undefined
rv

返回传递给生成器的next()方法的可选值,以恢复其执行。

描述

yield关键字使生成器函数执行暂停,yield关键字后面的表达式的值返回给生成器的调用者。它可以被认为是一个基于生成器的版本的return关键字。

yield关键字实际返回一个IteratorResult对象,它有两个属性,valuedonevalue属性是对yield表达式求值的结果,而donefalse,表示生成器函数尚未完全完成。

一旦遇到 yield 表达式,生成器的代码将被暂停运行,直到生成器的 next() 方法被调用。每次调用生成器的next()方法时,生成器都会恢复执行,直到达到以下某个值:

  • yield,导致生成器再次暂停并返回生成器的新值。 下一次调用next()时,在yield之后紧接着的语句继续执行。
  • throw用于从生成器中抛出异常。这让生成器完全停止执行,并在调用者中继续执行,正如通常情况下抛出异常一样。
  • 到达生成器函数的结尾;在这种情况下,生成器的执行结束,并且IteratorResult给调用者返回undefined并且donetrue
  • 到达return 语句。在这种情况下,生成器的执行结束,并将IteratorResult返回给调用者,其值是由return语句指定的,并且done 为true

如果将参数传递给生成器的next()方法,则该值将成为生成器当前yield操作返回的值。

在生成器的代码路径中的yield运算符,以及通过将其传递给Generator.prototype.next()指定新的起始值的能力之间,生成器提供了强大的控制力。

示例

以下代码是一个生成器函数的声明。

function* countAppleSales () {
  var saleList = [3, 7, 5];
  for (var i = 0; i < saleList.length; i++) {
    yield saleList[i];
  }
}

一旦生成器函数已定义,可以通过构造一个迭代器来使用它。

var appleStore = countAppleSales(); // Generator { }
console.log(appleStore.next()); // { value: 3, done: false }
console.log(appleStore.next()); // { value: 7, done: false }
console.log(appleStore.next()); // { value: 5, done: false }
console.log(appleStore.next()); // { value: undefined, done: true }

规范

Specification Status Comment
ECMAScript 2015 (6th Edition, ECMA-262)
Yield
Standard Initial definition.
ECMAScript Latest Draft (ECMA-262)
Yield
Draft  

浏览器兼容性

Update compatibility data on GitHub
Desktop Mobile Server
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.js
yield Chrome Full support 39 Edge Full support 12 Firefox Full support 26
Notes
Full support 26
Notes
Notes Starting with Firefox 33, the parsing of the yield expression has been updated to conform with the ES2015 specification.
Notes Starting with Firefox 29, an IteratorResult object returned for completed generator function.
IE No support No Opera Full support Yes Safari Full support 10 WebView Android Full support 39 Chrome Android Full support 39 Firefox Android Full support 26
Notes
Full support 26
Notes
Notes Starting with Firefox 33, the parsing of the yield expression has been updated to conform with the ES2015 specification.
Notes Starting with Firefox 29, an IteratorResult object returned for completed generator function.
Opera Android Full support Yes Safari iOS Full support 10 Samsung Internet Android Full support 4.0 nodejs Full support 4.0.0
Full support 4.0.0
Full support 0.12
Disabled
Disabled From version 0.12: this feature is behind the --harmony runtime flag.

Legend

Full support  
Full support
No support  
No support
See implementation notes.
See implementation notes.
User must explicitly enable this feature.
User must explicitly enable this feature.

相关链接