Skip to content

Instantly share code, notes, and snippets.

@juanmaguitar
Last active September 29, 2016 19:28
Show Gist options
  • Save juanmaguitar/d657f6ee295fb1b9acd2d5aa6aa40f98 to your computer and use it in GitHub Desktop.
Save juanmaguitar/d657f6ee295fb1b9acd2d5aa6aa40f98 to your computer and use it in GitHub Desktop.
Generators -ES2015
# Generators - ES2015
http://riadbenguella.com/how-es6-generators-are-changing-how-we-write-javascript/
Generators are special functions that can be run, paused and resumed at different stages of their execution, thanks to the special keyword `yield`.
```javascript
function* myGenerator() {
yield 'first';
let input = yield 'second';
yield input;
}
// Getting the generator object
let gen = myGenerator();
// Launching the generator
console.log( gen.next() ): // { value: 'first', done: false }
// First resume (no passed value)
console.log( gen.next() ); // { value: 'second', done: false }
// First resume (pass a value)
console.log( gen.next('third') ); // { value: 'third', done: false }
// Last (no more yield)
console.log( gen.next() ); // { value: undefined, done: true }
```
## Generators as iterators
```javascript
function* myGenerator() {
yield 'first';
yield 'second';
yield 'third';
}
for (var v of myGenerator()) {
console.log(v);
}
```
## Asynchronous control flow
Having this...
```javascript
function login(username, password) {
return fetch('/login', {
method: 'post',
body: JSON.stringify({
username: username
password: password
})
}).then(response => response.json());
}
function getPosts(token) {
return fetch('/posts', {
headers: new Headers({
'X-Security-Token': token
})
}).then(response => response.json());
}
```
We can go from this...
```javascript
const username = '';
const password = '';
login(username, password)
.then(result => getPosts(result.token))
.then(posts => {
console.log(posts);
})
.catch(err => {
console.log(err);
})
;
```
To this...
```javascript
co(function* () {
var result = yield login(username, password);
var posts = yield getPosts(result.token);
return posts;
}).then(value => {
console.log(value);
}, err => {
console.error(err);
});
```
## From express to Koa
----------
## More info
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*
- https://ponyfoo.com/articles/es6-generators-in-depth
- https://ponyfoo.com/articles/asynchronous-i-o-with-generators-and-promises
- http://riadbenguella.com/how-es6-generators-are-changing-how-we-write-javascript/
- http://stackoverflow.com/questions/37792303/es6-generator-function-vs-promises
- http://stackoverflow.com/questions/28031289/javascript-asynchronous-programming-promises-vs-generators
- http://tobyho.com/2015/12/27/promise-based-coroutines-nodejs/
- http://codinginadtech.com/posts/es6-and-beyond-part-2/
- http://www.2ality.com/2015/03/es6-generators.html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment