Javascript ES6 generators

Ramesh Nair
Ramesh NairFreelance Software Developer at HiddenTao Ltd
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 ?
1 of 22

Recommended

AngularJS for Beginners by
AngularJS for BeginnersAngularJS for Beginners
AngularJS for BeginnersEdureka!
8.4K views33 slides
Symfony presentation by
Symfony presentationSymfony presentation
Symfony presentationmaxpower57
1.2K views18 slides
Basics of JavaScript by
Basics of JavaScriptBasics of JavaScript
Basics of JavaScriptBala Narayanan
10.1K views29 slides
Php introduction by
Php introductionPhp introduction
Php introductionkrishnapriya Tadepalli
8.7K views28 slides
How Cascading Style Sheets (CSS) Works by
How Cascading Style Sheets (CSS) WorksHow Cascading Style Sheets (CSS) Works
How Cascading Style Sheets (CSS) WorksAmit Tyagi
79.4K views38 slides

More Related Content

What's hot

Wpf Introduction by
Wpf IntroductionWpf Introduction
Wpf IntroductionMartha Rotter
3.2K views73 slides
jQuery for beginners by
jQuery for beginnersjQuery for beginners
jQuery for beginnersArulmurugan Rajaraman
34.7K views22 slides
php by
phpphp
phpajeetjhajharia
65.4K views24 slides
Xml presentation by
Xml presentationXml presentation
Xml presentationMiguel Angel Teheran Garcia
5.6K views25 slides
Java Servlets by
Java ServletsJava Servlets
Java ServletsBG Java EE Course
31K views58 slides
HTML5, CSS, JavaScript Style guide and coding conventions by
HTML5, CSS, JavaScript Style guide and coding conventionsHTML5, CSS, JavaScript Style guide and coding conventions
HTML5, CSS, JavaScript Style guide and coding conventionsKnoldus Inc.
5.8K views37 slides

What's hot(20)

HTML5, CSS, JavaScript Style guide and coding conventions by Knoldus Inc.
HTML5, CSS, JavaScript Style guide and coding conventionsHTML5, CSS, JavaScript Style guide and coding conventions
HTML5, CSS, JavaScript Style guide and coding conventions
Knoldus Inc.5.8K views
JavaScript - Chapter 4 - Types and Statements by WebStackAcademy
 JavaScript - Chapter 4 - Types and Statements JavaScript - Chapter 4 - Types and Statements
JavaScript - Chapter 4 - Types and Statements
WebStackAcademy1.5K views
React new features and intro to Hooks by Soluto
React new features and intro to HooksReact new features and intro to Hooks
React new features and intro to Hooks
Soluto901 views
Hibernate ppt by Aneega
Hibernate pptHibernate ppt
Hibernate ppt
Aneega1.8K views
ASP.NET MVC Presentation by ivpol
ASP.NET MVC PresentationASP.NET MVC Presentation
ASP.NET MVC Presentation
ivpol23.6K views
Introduction to ajax by Pihu Goel
Introduction  to  ajaxIntroduction  to  ajax
Introduction to ajax
Pihu Goel895 views
JavaScript - An Introduction by Manvendra Singh
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An Introduction
Manvendra Singh19.1K views
What is component in reactjs by manojbkalla
What is component in reactjsWhat is component in reactjs
What is component in reactjs
manojbkalla177 views
Event In JavaScript by ShahDhruv21
Event In JavaScriptEvent In JavaScript
Event In JavaScript
ShahDhruv213.2K views
XML Schema by yht4ever
XML SchemaXML Schema
XML Schema
yht4ever6K views

Similar to Javascript ES6 generators

Web Optimization Summit: Coding for Performance by
Web Optimization Summit: Coding for PerformanceWeb Optimization Summit: Coding for Performance
Web Optimization Summit: Coding for Performancejohndaviddalton
541 views30 slides
Jsphp 110312161301-phpapp02 by
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Seri Moth
514 views87 slides
EcmaScript 6 by
EcmaScript 6 EcmaScript 6
EcmaScript 6 Manoj Kumar
1.7K views118 slides
JavaScript for PHP developers by
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developersStoyan Stefanov
15.6K views84 slides
Adding ES6 to Your Developer Toolbox by
Adding ES6 to Your Developer ToolboxAdding ES6 to Your Developer Toolbox
Adding ES6 to Your Developer ToolboxJeff Strauss
541 views124 slides
04 Advanced Javascript by
04 Advanced Javascript04 Advanced Javascript
04 Advanced Javascriptcrgwbr
524 views63 slides

Similar to Javascript ES6 generators(20)

Web Optimization Summit: Coding for Performance by johndaviddalton
Web Optimization Summit: Coding for PerformanceWeb Optimization Summit: Coding for Performance
Web Optimization Summit: Coding for Performance
johndaviddalton541 views
Jsphp 110312161301-phpapp02 by Seri Moth
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02
Seri Moth514 views
EcmaScript 6 by Manoj Kumar
EcmaScript 6 EcmaScript 6
EcmaScript 6
Manoj Kumar1.7K views
JavaScript for PHP developers by Stoyan Stefanov
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
Stoyan Stefanov15.6K views
Adding ES6 to Your Developer Toolbox by Jeff Strauss
Adding ES6 to Your Developer ToolboxAdding ES6 to Your Developer Toolbox
Adding ES6 to Your Developer Toolbox
Jeff Strauss541 views
04 Advanced Javascript by crgwbr
04 Advanced Javascript04 Advanced Javascript
04 Advanced Javascript
crgwbr524 views
Intro to Advanced JavaScript by ryanstout
Intro to Advanced JavaScriptIntro to Advanced JavaScript
Intro to Advanced JavaScript
ryanstout599 views
The redux saga begins by Daniel Franz
The redux saga beginsThe redux saga begins
The redux saga begins
Daniel Franz1.3K views
JSLab. Домников Виталий. "ES6 генераторы и Koa.js" by GeeksLab Odessa
JSLab. Домников Виталий. "ES6 генераторы и Koa.js"JSLab. Домников Виталий. "ES6 генераторы и Koa.js"
JSLab. Домников Виталий. "ES6 генераторы и Koa.js"
GeeksLab Odessa582 views
Fat Arrow (ES6) by Ryan Ewing
Fat Arrow (ES6)Fat Arrow (ES6)
Fat Arrow (ES6)
Ryan Ewing1.1K views
ES6 PPT FOR 2016 by Manoj Kumar
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
Manoj Kumar2.8K views
No excuses, switch to kotlin by Thijs Suijten
No excuses, switch to kotlinNo excuses, switch to kotlin
No excuses, switch to kotlin
Thijs Suijten300 views
Introduction to Kotlin.pptx by AzharFauzan9
Introduction to Kotlin.pptxIntroduction to Kotlin.pptx
Introduction to Kotlin.pptx
AzharFauzan94 views
Functional Programming in PHP by pwmosquito
Functional Programming in PHPFunctional Programming in PHP
Functional Programming in PHP
pwmosquito1.9K views
Introduction to ECMAScript 2015 by Tomasz Dziuda
Introduction to ECMAScript 2015Introduction to ECMAScript 2015
Introduction to ECMAScript 2015
Tomasz Dziuda859 views

More from Ramesh Nair

solUI Introduction (2019) by
solUI Introduction (2019)solUI Introduction (2019)
solUI Introduction (2019)Ramesh Nair
34 views21 slides
Kickback - incentivizing event attendance through crypto economics by
Kickback - incentivizing event attendance through crypto economicsKickback - incentivizing event attendance through crypto economics
Kickback - incentivizing event attendance through crypto economicsRamesh Nair
407 views22 slides
Introduction to Blockchains by
Introduction to BlockchainsIntroduction to Blockchains
Introduction to BlockchainsRamesh Nair
157 views72 slides
Introduction to PhoneGap by
Introduction to PhoneGapIntroduction to PhoneGap
Introduction to PhoneGapRamesh Nair
3.9K views15 slides
Introduction to Dart by
Introduction to DartIntroduction to Dart
Introduction to DartRamesh Nair
2.5K views46 slides
ES6 - Next Generation Javascript by
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation JavascriptRamesh Nair
12.3K views147 slides

More from Ramesh Nair(7)

solUI Introduction (2019) by Ramesh Nair
solUI Introduction (2019)solUI Introduction (2019)
solUI Introduction (2019)
Ramesh Nair34 views
Kickback - incentivizing event attendance through crypto economics by Ramesh Nair
Kickback - incentivizing event attendance through crypto economicsKickback - incentivizing event attendance through crypto economics
Kickback - incentivizing event attendance through crypto economics
Ramesh Nair407 views
Introduction to Blockchains by Ramesh Nair
Introduction to BlockchainsIntroduction to Blockchains
Introduction to Blockchains
Ramesh Nair157 views
Introduction to PhoneGap by Ramesh Nair
Introduction to PhoneGapIntroduction to PhoneGap
Introduction to PhoneGap
Ramesh Nair3.9K views
Introduction to Dart by Ramesh Nair
Introduction to DartIntroduction to Dart
Introduction to Dart
Ramesh Nair2.5K views
ES6 - Next Generation Javascript by Ramesh Nair
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
Ramesh Nair12.3K views
Javascript Update May 2013 by Ramesh Nair
Javascript Update May 2013Javascript Update May 2013
Javascript Update May 2013
Ramesh Nair2.5K views

Recently uploaded

20231123_Camunda Meetup Vienna.pdf by
20231123_Camunda Meetup Vienna.pdf20231123_Camunda Meetup Vienna.pdf
20231123_Camunda Meetup Vienna.pdfPhactum Softwareentwicklung GmbH
46 views73 slides
How to Re-use Old Hardware with CloudStack. Saving Money and the Environment ... by
How to Re-use Old Hardware with CloudStack. Saving Money and the Environment ...How to Re-use Old Hardware with CloudStack. Saving Money and the Environment ...
How to Re-use Old Hardware with CloudStack. Saving Money and the Environment ...ShapeBlue
65 views28 slides
Transitioning from VMware vCloud to Apache CloudStack: A Path to Profitabilit... by
Transitioning from VMware vCloud to Apache CloudStack: A Path to Profitabilit...Transitioning from VMware vCloud to Apache CloudStack: A Path to Profitabilit...
Transitioning from VMware vCloud to Apache CloudStack: A Path to Profitabilit...ShapeBlue
57 views25 slides
"Surviving highload with Node.js", Andrii Shumada by
"Surviving highload with Node.js", Andrii Shumada "Surviving highload with Node.js", Andrii Shumada
"Surviving highload with Node.js", Andrii Shumada Fwdays
40 views29 slides
DRBD Deep Dive - Philipp Reisner - LINBIT by
DRBD Deep Dive - Philipp Reisner - LINBITDRBD Deep Dive - Philipp Reisner - LINBIT
DRBD Deep Dive - Philipp Reisner - LINBITShapeBlue
62 views21 slides
Microsoft Power Platform.pptx by
Microsoft Power Platform.pptxMicrosoft Power Platform.pptx
Microsoft Power Platform.pptxUni Systems S.M.S.A.
67 views38 slides

Recently uploaded(20)

How to Re-use Old Hardware with CloudStack. Saving Money and the Environment ... by ShapeBlue
How to Re-use Old Hardware with CloudStack. Saving Money and the Environment ...How to Re-use Old Hardware with CloudStack. Saving Money and the Environment ...
How to Re-use Old Hardware with CloudStack. Saving Money and the Environment ...
ShapeBlue65 views
Transitioning from VMware vCloud to Apache CloudStack: A Path to Profitabilit... by ShapeBlue
Transitioning from VMware vCloud to Apache CloudStack: A Path to Profitabilit...Transitioning from VMware vCloud to Apache CloudStack: A Path to Profitabilit...
Transitioning from VMware vCloud to Apache CloudStack: A Path to Profitabilit...
ShapeBlue57 views
"Surviving highload with Node.js", Andrii Shumada by Fwdays
"Surviving highload with Node.js", Andrii Shumada "Surviving highload with Node.js", Andrii Shumada
"Surviving highload with Node.js", Andrii Shumada
Fwdays40 views
DRBD Deep Dive - Philipp Reisner - LINBIT by ShapeBlue
DRBD Deep Dive - Philipp Reisner - LINBITDRBD Deep Dive - Philipp Reisner - LINBIT
DRBD Deep Dive - Philipp Reisner - LINBIT
ShapeBlue62 views
Updates on the LINSTOR Driver for CloudStack - Rene Peinthor - LINBIT by ShapeBlue
Updates on the LINSTOR Driver for CloudStack - Rene Peinthor - LINBITUpdates on the LINSTOR Driver for CloudStack - Rene Peinthor - LINBIT
Updates on the LINSTOR Driver for CloudStack - Rene Peinthor - LINBIT
ShapeBlue91 views
Don’t Make A Human Do A Robot’s Job! : 6 Reasons Why AI Will Save Us & Not De... by Moses Kemibaro
Don’t Make A Human Do A Robot’s Job! : 6 Reasons Why AI Will Save Us & Not De...Don’t Make A Human Do A Robot’s Job! : 6 Reasons Why AI Will Save Us & Not De...
Don’t Make A Human Do A Robot’s Job! : 6 Reasons Why AI Will Save Us & Not De...
Moses Kemibaro29 views
Business Analyst Series 2023 - Week 4 Session 7 by DianaGray10
Business Analyst Series 2023 -  Week 4 Session 7Business Analyst Series 2023 -  Week 4 Session 7
Business Analyst Series 2023 - Week 4 Session 7
DianaGray1080 views
Hypervisor Agnostic DRS in CloudStack - Brief overview & demo - Vishesh Jinda... by ShapeBlue
Hypervisor Agnostic DRS in CloudStack - Brief overview & demo - Vishesh Jinda...Hypervisor Agnostic DRS in CloudStack - Brief overview & demo - Vishesh Jinda...
Hypervisor Agnostic DRS in CloudStack - Brief overview & demo - Vishesh Jinda...
ShapeBlue63 views
CloudStack Object Storage - An Introduction - Vladimir Petrov - ShapeBlue by ShapeBlue
CloudStack Object Storage - An Introduction - Vladimir Petrov - ShapeBlueCloudStack Object Storage - An Introduction - Vladimir Petrov - ShapeBlue
CloudStack Object Storage - An Introduction - Vladimir Petrov - ShapeBlue
ShapeBlue46 views
Why and How CloudStack at weSystems - Stephan Bienek - weSystems by ShapeBlue
Why and How CloudStack at weSystems - Stephan Bienek - weSystemsWhy and How CloudStack at weSystems - Stephan Bienek - weSystems
Why and How CloudStack at weSystems - Stephan Bienek - weSystems
ShapeBlue111 views
What’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlue by ShapeBlue
What’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlueWhat’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlue
What’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlue
ShapeBlue131 views
Elevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlue by ShapeBlue
Elevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlueElevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlue
Elevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlue
ShapeBlue96 views
KVM Security Groups Under the Hood - Wido den Hollander - Your.Online by ShapeBlue
KVM Security Groups Under the Hood - Wido den Hollander - Your.OnlineKVM Security Groups Under the Hood - Wido den Hollander - Your.Online
KVM Security Groups Under the Hood - Wido den Hollander - Your.Online
ShapeBlue102 views
Migrating VMware Infra to KVM Using CloudStack - Nicolas Vazquez - ShapeBlue by ShapeBlue
Migrating VMware Infra to KVM Using CloudStack - Nicolas Vazquez - ShapeBlueMigrating VMware Infra to KVM Using CloudStack - Nicolas Vazquez - ShapeBlue
Migrating VMware Infra to KVM Using CloudStack - Nicolas Vazquez - ShapeBlue
ShapeBlue96 views
TrustArc Webinar - Managing Online Tracking Technology Vendors_ A Checklist f... by TrustArc
TrustArc Webinar - Managing Online Tracking Technology Vendors_ A Checklist f...TrustArc Webinar - Managing Online Tracking Technology Vendors_ A Checklist f...
TrustArc Webinar - Managing Online Tracking Technology Vendors_ A Checklist f...
TrustArc77 views

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 ?