Generators in JavaScript are a special kind of function that can be paused and resumed. This can be useful for handling asynchronous tasks. Here’s how you use them:
1. Define a generator function. This is done by adding an asterisk (\*) after the `function` keyword.
```
function* generatorFunction() {
console.log(‘This will be executed first.’);
yield ‘Hello, ‘;
The `yield` keyword is used to pause the generator. When the generator is resumed, the value after `yield` is the result of the pause.
1. Create a generator object. You do this by calling the generator function, which returns a generator object.
```
const generatorObject = generatorFunction();
```
1. Use the generator. Generators are iterators, which means they have a `next()` method which resumes the generator and returns an object with two properties: `value` and `done`.
```
console.log(generatorObject.next()); // This will be executed first.
// {value: “Hello, “, done: false}
console.log(generatorObject.next()); // I will be printed after the pause // {value: “World!”, done: false}
console.log(generatorObject.next()); // {value: undefined, done: true}
```
After calling `next()` the first time, the generator is resumed until it hits the `yield ‘Hello, ‘;` statement. This pauses the generator and returns `{value: “Hello, “, done: false}`.
Once `next()` is called again, the generator is resumed until it hits the `yield ‘World!’;` statement. This pauses the generator again and returns `{value: “World!”, done: false}`.
The next time `next()` is called, there are no more `yield` statements and the generator function ends, returning `{value: undefined, done: true}`.
The `done` property is `false` as long as the generator has not reached the end. Once there are no more `yield` statements, `done` will be `true`. The `value` property holds whatever value was yielded. If there is no yield left, `value` will be `undefined`.