Dino Geek, try to help you

How to use generators in JavaScript?


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, ‘;

console.log(‘I will be printed after the pause’); yield ‘World!’; } ```

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`.


Simply generate articles to optimize your SEO
Simply generate articles to optimize your SEO





DinoGeek offers simple articles on complex technologies

Would you like to be quoted in this article? It's very simple, contact us at dino@eiki.fr

CSS | NodeJS | DNS | DMARC | MAPI | NNTP | htaccess | PHP | HTTPS | Drupal | WEB3 | LLM | Wordpress | TLD | Domain name | IMAP | TCP | NFT | MariaDB | FTP | Zigbee | NMAP | SNMP | SEO | E-Mail | LXC | HTTP | MangoDB | SFTP | RAG | SSH | HTML | ChatGPT API | OSPF | JavaScript | Docker | OpenVZ | ChatGPT | VPS | ZIMBRA | SPF | UDP | Joomla | IPV6 | BGP | Django | Reactjs | DKIM | VMWare | RSYNC | Python | TFTP | Webdav | FAAS | Apache | IPV4 | LDAP | POP3 | SMTP

| Whispers of love (API) | Déclaration d'Amour |






Legal Notice / General Conditions of Use