Generators in TypeScript (Live Playground)
In this tutorial, we will explore generators and iterators in TypeScript, which provide an alternative way to manage asynchronous tasks using a more concise syntax and a better control flow.
What are Generators?
Generators are special functions in TypeScript that allow you to create and manage iterators. They are declared using the function* syntax and can be paused and resumed using the yield keyword.
function* myGenerator() {
  yield 1;
  yield 2;
  yield 3;
}
What are Iterators?
Iterators are objects that implement a next() method, which returns the next value in a sequence. Iterators also have a done property, which indicates whether the iterator has reached the end of the sequence.
const iterator = myGenerator();
console.log(iterator.next()); // { value: 1, done: false }
console.log(iterator.next()); // { value: 2, done: false }
console.log(iterator.next()); // { value: 3, done: false }
console.log(iterator.next()); // { value: undefined, done: true }
Using Generators with Async/Await
Generators can be combined with async/await to create a more concise and readable way to manage asynchronous tasks.
async function* fetchItems(): AsyncIterable<string> {
  for (let i = 0; i < 3; i++) {
    await new Promise(resolve => setTimeout(resolve, 1000));
    yield `Item ${i}`;
  }
}
async function processItems(): Promise<void> {
  const iterator = fetchItems();
  for await (const item of iterator) {
    console.log(item);
  }
}
processItems();
Using Generators with Promises
Generators can also be combined with Promises to create a more readable way to manage asynchronous tasks.
function* fetchItems(): Iterable<Promise<string>> {
  for (let i = 0; i < 3; i++) {
    yield new Promise(resolve => setTimeout(() => resolve(`Item ${i}`), 1000));
  }
}
async function processItems(): Promise<void> {
  const iterator = fetchItems();
  for (const itemPromise of iterator) {
    const item = await itemPromise;
    console.log(item);
  }
}
processItems();
Conclusion
In this tutorial, we have explored generators and iterators in TypeScript, which provide an alternative way to manage asynchronous tasks using a more concise syntax and a better control flow. As you continue learning TypeScript, make sure to practice using generators and iterators, along with other async programming techniques like callbacks, Promises, and async/await, to manage asynchronous tasks efficiently in your applications.