Search⌘ K

Generators

Explore the concept of generators in JavaScript ES6, including how to create and control generator functions using yield and next. Understand looping, error handling with throw, finishing generators with return, and combining generators with promises to write asynchronous code that behaves synchronously.

What is a generator? #

A generator function is a function that we can start and stop, for an indefinite amount of time. And also restart with the possibility of passing additional data at a later point in time.

To create a generator function we write like this:

Javascript (babel-node)
function* fruitList(){
yield 'Banana';
yield 'Apple';
yield 'Orange';
}
const fruits = fruitList();
fruits;
// Generator
console.log(fruits.next());
// Object { value: "Banana", done: false }
console.log(fruits.next());
// Object { value: "Apple", done: false }
console.log(fruits.next());
// Object { value: "Orange", done: false }
console.log(fruits.next());
// Object { value: undefined, done: true }

Let’s have a look at the code piece by piece:

  • we declared the function using function*
  • we used the keyword yield before our content
  • we start our function using .next()
  • the last time we call .next() we receive and empty object and we get
...