SlideShare a Scribd company logo
E S 6 G E N E R AT O R S
R A M E S H N A I R
H I D D E N TA O . C O M
!
A U G U S T 1 3 , 2 0 1 4
TA I P E I J A VA S C R I P T E N T H U S I A S T S
G E N E R AT O R
A Generator generates values
…
Until no more values are available
S I M P L E G E N E R AT O R
var helloWorld = function*() {!
yield 'hello';!
yield 'world';!
}	

This function
returns
a generatorThis generator
“yields”
two strings
S T E P - B Y- S T E P
{ value: 'hello', done: false }
var gen = helloWorld();
var helloWorld = function*() {!
yield 'hello';!
yield 'world';!
}
var value1 = gen.next();
console.log( value1 );
var value2 = gen.next();
console.log( value2 );
{ value: 'world', done: false }
var value3 = gen.next();
console.log( value3 );
{value: undefined, done: true}
F I B O N A C C I
var fib = function*() {	
let [prev, curr] = [0, 1];	
for (;;) {	
[prev, curr] = [curr, prev + curr];	
yield curr;	
}	
}
1, 2, 3, 5, 8, 13, 21, …
F O R - O F
var fib = function*() {	
let [prev, curr] = [0, 1];	
for (;;) {	
[prev, curr] = [curr, prev + curr];	
yield curr;	
}	
}	
!
for (let n of fib()) {	
print(n); // 1, 2, 3, 5, 8, 13,…	
}
But yielding values isn’t that useful on its own
What if we could feed values back in?
F E E D I N G
{ value: 'hello', done: false }
var gen = helloWorld();
var value1 = gen.next();
console.log( value1 );
var value2 = gen.next(‘my’);
console.log( value2 );
{ value: ‘my world', done: false }
var helloWorld = function*() {!
var v = yield 'hello';!
yield v + ' world';!
}
A yield
is
synchronous
So what would happen if we yielded a Promise?
Y I E L D P R O M I S E S
Looks like
a synchronous
call!
var gen = showUser();
var promise = gen.next().value;
promise.then(function(user) {!
! gen.next(user);!
});
var showUser = function*() {!
var user = yield $.get(“/getUser?id=1”);!
alert( user.name );!
}
Y I E L D M A N Y P R O M I S E S
var gen = showStats();
var promise1 = gen.next().value;
promise1.then(function(user) {!
!
!
!
!
});
var showStats = function*() {!
var user = yield $.get(“/getUser?name=bob”);!
var stats = yield $.get(“/stats/” + user.id);!
! …!
}
Repeats
! ! promise2.then(function(stats) {!
! ! ! gen.next(stats);!
! ! });!
var promise2 = gen.next(user).value;
C O - R O U T I N E S
var co = function(gen) {!
! (var _next = function(res) {!
! ! var yielded = gen.next(res);!
! ! if (!yielded.done) {!
! ! ! yielded.value.then(_next);!
! ! }!
! })();!
}!
!
co(showStats());
var showStats = function*() {!
var user = yield $.get(“/getUser?name=bob”);!
var stats = yield $.get(“/stats/” + user.id);!
! …!
}
E R R O R S
var gen = showUser();
var promise = gen.next().value;
promise.then(function(user) {!
! gen.next(user);!
})
var showUser = function*() {!
!
!
!
!
!
}
! .catch(function(err) {!
!! gen.throw(err);!
! });
yield $.get(“/getUser?id=1”);
try {!
! ! !
} catch (err) {!
// do something!
}!
Can yield
inside here
G E N E R AT E D E R R O R S
var gen = showUser();
try {!
! var promise = gen.next().value;!
} catch (err) {!
console.error(err);!
}!
var showUser = function*() {!
throw new Error(‘fail’);!
}
B E T T E R C O - R O U T I N E
var co = function(gen) {	
(var _next = function(err, res) {	
try {	
var yld = null;	
!
if (err) {	
yld = gen.throw(err);	
} else {	
yld = gen.next(res);	
}	
!
if (!yld.done) {	
yld.value.then(function(result){	
_next(null, result);	
}).catch(_next);	
}	
} catch (err) {	
console.error(err);	
}	
})();	
};
C O - R O U T I N E M O D U L E S
• Bluebird
• Promise.coroutine()
• Returns a Promise
• Lets you yield promises. Must configure it to support other item types.
• co
• co()!
• Accepts a callback
• Lets you yield promises, thunks, generators, generator functions
Faster for
Promises
More flexible
yielding
P R O M I S E S - > G E N E R AT O R S
var readFile = // returns a Promise	
!
var main = function() {	
return readFile('file1')	
.then(function(contents) {	
console.log(contents);	
return readFile('file2');	
})	
.then(function(contents) {	
console.log(contents);	
})	
}	
!
main().catch(…);
var readFile = // returns a Promise	
!
var main = function*() {	
console.log(yield readFile('file1'));	
console.log(yield readFile('file2')); 	
}	
!
co(main)(…);
PA R A L L E L P R O C E S S I N G
var readFile = // returns a Promise	
!
var main = function*() {	
var files = [	
yield readFile('file1'),	
yield readFile('file2')	
];	
... // do stuff with files	
}	
!
co(main)();
var readFile = // returns a Promise	
!
var main = function*() {	
var files = yield [	
readFile('file1'),	
readFile('file2')	
];	
... // do stuff with files	
}	
!
co(main)();
sequential parallel
E X P R E S S - > K O A
var express = require('express');	
var app = express();	
!
app.use(function(req, res, next){	
res.send('Hello World');	
});	
!
app.listen(3000);
var koa = require('koa');	
var app = koa();	
!
app.use(function*(next){	
this.body = 'Hello World';	
});	
!
app.listen(3000);
Easier to control order of middleware execution…
K O A M I D D L E WA R E
• Waigo (waigojs.com) - web framework built around Koa
var koa = require('koa');	
var app = koa();	
!
app.use(function*(next) {	
try {	
yield next;	
} catch (err) {	
// handle err	
}	
});	
!
app.use(function*(next){	
throw new Error('test');	
});
Execute rest
of chain
A L S O C H E C K O U T…
• Iterators
• Simpler than generators
• Only return values, no feeding back in
• await!
• ES7 onwards
A N Y Q U E S T I O N S ?

More Related Content

PDF
Unicode basics in python
PPTX
Interfaces in java
PPT
Method overriding
PPTX
Type casting in java
PPTX
Core java complete ppt(note)
PPT
Strings
PPTX
Data Structures - Lecture 7 [Linked List]
ODP
Python Modules
Unicode basics in python
Interfaces in java
Method overriding
Type casting in java
Core java complete ppt(note)
Strings
Data Structures - Lecture 7 [Linked List]
Python Modules

What's hot (20)

PPTX
OOPS In JAVA.pptx
PPTX
Loops in java script
PDF
Chapter 7 - Input Output Statements in C++
PDF
Inheritance
PDF
CSS Unit I - Basics of JavaScript Programming
PPTX
Inner classes in java
PDF
Python twisted
PPTX
What is component in reactjs
PPT
Types of exceptions
PPTX
Unix shell scripts
PPTX
Loops in C
PDF
Pros & cons of svelte
PPTX
Properties and indexers in C#
PDF
JavaScript - Chapter 6 - Basic Functions
PPTX
PDF
Java threads
PDF
OOP Assignment 03.pdf
PDF
basic of desicion control statement in python
PDF
ES6 presentation
OOPS In JAVA.pptx
Loops in java script
Chapter 7 - Input Output Statements in C++
Inheritance
CSS Unit I - Basics of JavaScript Programming
Inner classes in java
Python twisted
What is component in reactjs
Types of exceptions
Unix shell scripts
Loops in C
Pros & cons of svelte
Properties and indexers in C#
JavaScript - Chapter 6 - Basic Functions
Java threads
OOP Assignment 03.pdf
basic of desicion control statement in python
ES6 presentation
Ad

Similar to Javascript ES6 generators (20)

PPT
Web Optimization Summit: Coding for Performance
DOC
Jsphp 110312161301-phpapp02
ODP
EcmaScript 6
PDF
JavaScript for PHP developers
PDF
Adding ES6 to Your Developer Toolbox
PDF
04 Advanced Javascript
PDF
ES6: The future is now
PDF
Intro to Advanced JavaScript
PPTX
The redux saga begins
PDF
JSLab. Домников Виталий. "ES6 генераторы и Koa.js"
PDF
Fat Arrow (ES6)
ODP
ES6 PPT FOR 2016
PDF
ES6 generators
PDF
No excuses, switch to kotlin
PDF
Javascript essentials
PPTX
01 Introduction to Kotlin - Programming in Kotlin.pptx
PPTX
Introduction to Kotlin.pptx
PDF
Functional Programming in PHP
PDF
Short intro to ECMAScript
PDF
CoffeeScript
Web Optimization Summit: Coding for Performance
Jsphp 110312161301-phpapp02
EcmaScript 6
JavaScript for PHP developers
Adding ES6 to Your Developer Toolbox
04 Advanced Javascript
ES6: The future is now
Intro to Advanced JavaScript
The redux saga begins
JSLab. Домников Виталий. "ES6 генераторы и Koa.js"
Fat Arrow (ES6)
ES6 PPT FOR 2016
ES6 generators
No excuses, switch to kotlin
Javascript essentials
01 Introduction to Kotlin - Programming in Kotlin.pptx
Introduction to Kotlin.pptx
Functional Programming in PHP
Short intro to ECMAScript
CoffeeScript
Ad

More from RameshNair6 (7)

PDF
solUI Introduction (2019)
PDF
Kickback - incentivizing event attendance through crypto economics
PDF
Introduction to Blockchains
PDF
Introduction to PhoneGap
PDF
Introduction to Dart
PDF
ES6 - Next Generation Javascript
ODP
Javascript Update May 2013
solUI Introduction (2019)
Kickback - incentivizing event attendance through crypto economics
Introduction to Blockchains
Introduction to PhoneGap
Introduction to Dart
ES6 - Next Generation Javascript
Javascript Update May 2013

Recently uploaded (20)

PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Machine learning based COVID-19 study performance prediction
PDF
Approach and Philosophy of On baking technology
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
Advanced methodologies resolving dimensionality complications for autism neur...
Building Integrated photovoltaic BIPV_UPV.pdf
20250228 LYD VKU AI Blended-Learning.pptx
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
NewMind AI Monthly Chronicles - July 2025
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Understanding_Digital_Forensics_Presentation.pptx
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Machine learning based COVID-19 study performance prediction
Approach and Philosophy of On baking technology
Network Security Unit 5.pdf for BCA BBA.
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Encapsulation_ Review paper, used for researhc scholars
Digital-Transformation-Roadmap-for-Companies.pptx
MYSQL Presentation for SQL database connectivity
Reach Out and Touch Someone: Haptics and Empathic Computing
Review of recent advances in non-invasive hemoglobin estimation
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
The Rise and Fall of 3GPP – Time for a Sabbatical?

Javascript ES6 generators

  • 1. E S 6 G E N E R AT O R S R A M E S H N A I R H I D D E N TA O . C O M ! A U G U S T 1 3 , 2 0 1 4 TA I P E I J A VA S C R I P T E N T H U S I A S T S
  • 2. G E N E R AT O R A Generator generates values … Until no more values are available
  • 3. S I M P L E G E N E R AT O R var helloWorld = function*() {! yield 'hello';! yield 'world';! } This function returns a generatorThis generator “yields” two strings
  • 4. S T E P - B Y- S T E P { value: 'hello', done: false } var gen = helloWorld(); var helloWorld = function*() {! yield 'hello';! yield 'world';! } var value1 = gen.next(); console.log( value1 ); var value2 = gen.next(); console.log( value2 ); { value: 'world', done: false } var value3 = gen.next(); console.log( value3 ); {value: undefined, done: true}
  • 5. F I B O N A C C I var fib = function*() { let [prev, curr] = [0, 1]; for (;;) { [prev, curr] = [curr, prev + curr]; yield curr; } } 1, 2, 3, 5, 8, 13, 21, …
  • 6. F O R - O F var fib = function*() { let [prev, curr] = [0, 1]; for (;;) { [prev, curr] = [curr, prev + curr]; yield curr; } } ! for (let n of fib()) { print(n); // 1, 2, 3, 5, 8, 13,… }
  • 7. But yielding values isn’t that useful on its own What if we could feed values back in?
  • 8. F E E D I N G { value: 'hello', done: false } var gen = helloWorld(); var value1 = gen.next(); console.log( value1 ); var value2 = gen.next(‘my’); console.log( value2 ); { value: ‘my world', done: false } var helloWorld = function*() {! var v = yield 'hello';! yield v + ' world';! } A yield is synchronous
  • 9. So what would happen if we yielded a Promise?
  • 10. Y I E L D P R O M I S E S Looks like a synchronous call! var gen = showUser(); var promise = gen.next().value; promise.then(function(user) {! ! gen.next(user);! }); var showUser = function*() {! var user = yield $.get(“/getUser?id=1”);! alert( user.name );! }
  • 11. Y I E L D M A N Y P R O M I S E S var gen = showStats(); var promise1 = gen.next().value; promise1.then(function(user) {! ! ! ! ! }); var showStats = function*() {! var user = yield $.get(“/getUser?name=bob”);! var stats = yield $.get(“/stats/” + user.id);! ! …! } Repeats ! ! promise2.then(function(stats) {! ! ! ! gen.next(stats);! ! ! });! var promise2 = gen.next(user).value;
  • 12. C O - R O U T I N E S var co = function(gen) {! ! (var _next = function(res) {! ! ! var yielded = gen.next(res);! ! ! if (!yielded.done) {! ! ! ! yielded.value.then(_next);! ! ! }! ! })();! }! ! co(showStats()); var showStats = function*() {! var user = yield $.get(“/getUser?name=bob”);! var stats = yield $.get(“/stats/” + user.id);! ! …! }
  • 13. E R R O R S var gen = showUser(); var promise = gen.next().value; promise.then(function(user) {! ! gen.next(user);! }) var showUser = function*() {! ! ! ! ! ! } ! .catch(function(err) {! !! gen.throw(err);! ! }); yield $.get(“/getUser?id=1”); try {! ! ! ! } catch (err) {! // do something! }! Can yield inside here
  • 14. G E N E R AT E D E R R O R S var gen = showUser(); try {! ! var promise = gen.next().value;! } catch (err) {! console.error(err);! }! var showUser = function*() {! throw new Error(‘fail’);! }
  • 15. B E T T E R C O - R O U T I N E var co = function(gen) { (var _next = function(err, res) { try { var yld = null; ! if (err) { yld = gen.throw(err); } else { yld = gen.next(res); } ! if (!yld.done) { yld.value.then(function(result){ _next(null, result); }).catch(_next); } } catch (err) { console.error(err); } })(); };
  • 16. C O - R O U T I N E M O D U L E S • Bluebird • Promise.coroutine() • Returns a Promise • Lets you yield promises. Must configure it to support other item types. • co • co()! • Accepts a callback • Lets you yield promises, thunks, generators, generator functions Faster for Promises More flexible yielding
  • 17. P R O M I S E S - > G E N E R AT O R S var readFile = // returns a Promise ! var main = function() { return readFile('file1') .then(function(contents) { console.log(contents); return readFile('file2'); }) .then(function(contents) { console.log(contents); }) } ! main().catch(…); var readFile = // returns a Promise ! var main = function*() { console.log(yield readFile('file1')); console.log(yield readFile('file2')); } ! co(main)(…);
  • 18. PA R A L L E L P R O C E S S I N G var readFile = // returns a Promise ! var main = function*() { var files = [ yield readFile('file1'), yield readFile('file2') ]; ... // do stuff with files } ! co(main)(); var readFile = // returns a Promise ! var main = function*() { var files = yield [ readFile('file1'), readFile('file2') ]; ... // do stuff with files } ! co(main)(); sequential parallel
  • 19. E X P R E S S - > K O A var express = require('express'); var app = express(); ! app.use(function(req, res, next){ res.send('Hello World'); }); ! app.listen(3000); var koa = require('koa'); var app = koa(); ! app.use(function*(next){ this.body = 'Hello World'; }); ! app.listen(3000); Easier to control order of middleware execution…
  • 20. K O A M I D D L E WA R E • Waigo (waigojs.com) - web framework built around Koa var koa = require('koa'); var app = koa(); ! app.use(function*(next) { try { yield next; } catch (err) { // handle err } }); ! app.use(function*(next){ throw new Error('test'); }); Execute rest of chain
  • 21. A L S O C H E C K O U T… • Iterators • Simpler than generators • Only return values, no feeding back in • await! • ES7 onwards
  • 22. A N Y Q U E S T I O N S ?