Saltar al contenido principal
Curso/Asincronía/Generators
Volver a Asincronía

Asincronía — Leccion 4

·15 min

Generators

Funciones que pueden pausar y reanudar su ejecución.

Generators

Las funciones generadoras usan yield para pausar la ejecución.

typescript
function* contador() {
  yield 1;
  yield 2;
  yield 3;
}

const gen = contador();
gen.next(); // { value: 1, done: false }
gen.next(); // { value: 2, done: false }
gen.next(); // { value: 3, done: false }
gen.next(); // { value: undefined, done: true }

Iterando con for...of

typescript
function* numeros() {
  yield 1;
  yield 2;
  yield 3;
}

for (const num of numeros()) {
  console.log(num); // 1, 2, 3
}

Yield con valores

typescript
function* calculadora() {
  let resultado = 0;
  while (true) {
    const valor = yield resultado;
    resultado += valor;
  }
}

const calc = calculadora();
calc.next();      // { value: 0, done: false }
calc.next(5);     // { value: 5, done: false }
calc.next(3);     // { value: 8, done: false }
calc.next(10);    // { value: 18, done: false }

Generador infinito

typescript
function* fibonacci() {
  let a = 0, b = 1;
  while (true) {
    yield a;
    [a, b] = [b, a + b];
  }
}

const fib = fibonacci();
fib.next(); // 0
fib.next(); // 1
fib.next(); // 1
fib.next(); // 2

Ejercicio pratico

Crea un generator que genere numeros del 1 al 5.

exercise.ts
Loading...
Resultado

Haz clic en "Ejecutar" para ver el resultado...

Curso de TypeScript — Aprende desde cero