Esta traducción está incompleta. Por favor, ayuda a traducir este artículo del inglés.

La palabra clave yield se utiliza para pausar y reanudar una función  generadora (function* o una función generadora heredada).

Sintaxis

[rv] = yield [expresión];
expresión
Define el valor a devolver desde la función del generador a través del protocolo del iterador. Si se omite, se devuelve undefined en su lugar.
rv

Devuelve el valor opcional pasado por el metodo generador next() para continuar la ejecución.

Descripción

La palabra clave yield pausa la ejecución de la función generadora y el valor de la expresión siguiente de la clave yield es retornada al llamado del generador. Se puede considerar como una versión basada en generador de la palabra clave return.

La palabra clave yield en realidad devuelve un objeto IteratorResult con dos propiedades value y done. La propiedad value es el resultado de evaluar la expresión de yield, y done es false, indicando que la función del generador no se ha terminado completamente.

Once paused on a yield expression, the generator's code execution remains paused until the generator's next() method is called. Each time the generator's next() method is called, the generator resumes execution and runs until it reaches one of the following:

  •  A yield, which causes the generator to once again pause and return the generator's new value. The next time next() is called, execution resumes with the statement immediately after the yield.
  • throw is used to throw an exception from the generator. This halts execution of the generator entirely, and execution resumes in the caller as is normally the case when an exception is thrown.
  • The end of the generator function is reached; in this case, execution of the generator ends and an IteratorResult is returned to the caller in which the value is undefined and done is true.
  • A return statement is reached. In this case, execution of the generator ends and an IteratorResult is returned to the caller in which the value is the value specified by the return statement and done is true.

If an optional value is passed to the generator's next() method, that value becomes the value returned by the generator's current yield operation.

Between the generator's code path, its yield operators, and the ability to specify a new starting value by passing it to Generator.prototype.next(), generators offer enormous power and control.

Ejemplos

The following code is the declaration of an example generator function.

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

Once a generator function is defined, it can be used by constructing an iterator as shown.

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 }

Especificaciones

Specification Status Comment
ECMAScript 2015 (6th Edition, ECMA-262)
La definición de 'Yield' en esta especificación.
Standard Initial definition.
ECMAScript Latest Draft (ECMA-262)
La definición de 'Yield' en esta especificación.
Living Standard  

Compatibilidad del navegador

FeatureChromeEdgeFirefoxInternet ExplorerOperaSafari
Soporte básico39 Si261 No Si10
IteratorResult object instead of throwing ? ?29 No ?10
FeatureAndroid webviewChrome para AndroidEdge mobileFirefox para AndroidIE mobileOpera AndroidiOS Safari
Soporte básico3939 Si261 No Si10
IteratorResult object instead of throwing ? ? ?29 No ?10

1. Starting with Firefox 33, the parsing of the yield expression has been updated to conform with the ES2015 specification.

Notas específicas para Firefox

  • Starting with Gecko 29 (Firefox 29 / Thunderbird 29 / SeaMonkey 2.26), the completed generator function no longer throws a TypeError "generator has already finished". Instead, it returns an IteratorResult object like { value: undefined, done: true } (error 958951).
  • Starting with Gecko 33 (Firefox 33 / Thunderbird 33 / SeaMonkey 2.30), the parsing of the yield expression has been updated to conform with the ES2015 specification (error 981599):
    • The expression after the yield keyword is optional and omitting it no longer throws a SyntaxError: function* countAppleSales() { yield; }

Vea también

Etiquetas y colaboradores del documento

 Colaboradores en esta página: hamfree, juliandavidmr
 Última actualización por: hamfree,