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

What's hot

ES6 presentation
ES6 presentationES6 presentation
ES6 presentation
ritika1
 
Complete MVC on NodeJS
Complete MVC on NodeJSComplete MVC on NodeJS
Complete MVC on NodeJS
Hüseyin BABAL
 
Introduction to Azure Event Grid
Introduction to Azure Event GridIntroduction to Azure Event Grid
Introduction to Azure Event Grid
Callon Campbell
 
Kafka Tutorial: Kafka Security
Kafka Tutorial: Kafka SecurityKafka Tutorial: Kafka Security
Kafka Tutorial: Kafka Security
Jean-Paul Azar
 
Deconstructing Monoliths with Domain Driven Design
Deconstructing Monoliths with Domain Driven DesignDeconstructing Monoliths with Domain Driven Design
Deconstructing Monoliths with Domain Driven Design
VMware Tanzu
 
Terraform modules restructured
Terraform modules restructuredTerraform modules restructured
Terraform modules restructured
Ami Mahloof
 
Reactive Programming in Java 8 with Rx-Java
Reactive Programming in Java 8 with Rx-JavaReactive Programming in Java 8 with Rx-Java
Reactive Programming in Java 8 with Rx-Java
Kasun Indrasiri
 
An intro to Kubernetes operators
An intro to Kubernetes operatorsAn intro to Kubernetes operators
An intro to Kubernetes operators
J On The Beach
 
.Net Core
.Net Core.Net Core
.Net Core
Bertrand Le Roy
 
Build Your Own Angular Component Library
Build Your Own Angular Component LibraryBuild Your Own Angular Component Library
Build Your Own Angular Component Library
Carlo Bonamico
 
Kubernetes
KubernetesKubernetes
Kubernetes
Lhouceine OUHAMZA
 
Code quality for Terraform
Code quality for TerraformCode quality for Terraform
Code quality for Terraform
Mitchell Pronschinske
 
Capabilities for Resources and Effects
Capabilities for Resources and EffectsCapabilities for Resources and Effects
Capabilities for Resources and Effects
Martin Odersky
 
Devops - Microservice and Kubernetes
Devops - Microservice and KubernetesDevops - Microservice and Kubernetes
Devops - Microservice and Kubernetes
NodeXperts
 
Building .NET Microservices
Building .NET MicroservicesBuilding .NET Microservices
Building .NET Microservices
VMware Tanzu
 
Azure Interview Questions And Answers | Azure Tutorial For Beginners | Azure ...
Azure Interview Questions And Answers | Azure Tutorial For Beginners | Azure ...Azure Interview Questions And Answers | Azure Tutorial For Beginners | Azure ...
Azure Interview Questions And Answers | Azure Tutorial For Beginners | Azure ...
Edureka!
 
The New JavaScript: ES6
The New JavaScript: ES6The New JavaScript: ES6
The New JavaScript: ES6
Rob Eisenberg
 
Middleware in Asp.Net Core
Middleware in Asp.Net CoreMiddleware in Asp.Net Core
Middleware in Asp.Net Core
Shahriar Hossain
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooks
Samundra khatri
 
Introducing Amazon EKS Anywhere On Apache CloudStack
Introducing Amazon EKS Anywhere On Apache CloudStackIntroducing Amazon EKS Anywhere On Apache CloudStack
Introducing Amazon EKS Anywhere On Apache CloudStack
ShapeBlue
 

What's hot (20)

ES6 presentation
ES6 presentationES6 presentation
ES6 presentation
 
Complete MVC on NodeJS
Complete MVC on NodeJSComplete MVC on NodeJS
Complete MVC on NodeJS
 
Introduction to Azure Event Grid
Introduction to Azure Event GridIntroduction to Azure Event Grid
Introduction to Azure Event Grid
 
Kafka Tutorial: Kafka Security
Kafka Tutorial: Kafka SecurityKafka Tutorial: Kafka Security
Kafka Tutorial: Kafka Security
 
Deconstructing Monoliths with Domain Driven Design
Deconstructing Monoliths with Domain Driven DesignDeconstructing Monoliths with Domain Driven Design
Deconstructing Monoliths with Domain Driven Design
 
Terraform modules restructured
Terraform modules restructuredTerraform modules restructured
Terraform modules restructured
 
Reactive Programming in Java 8 with Rx-Java
Reactive Programming in Java 8 with Rx-JavaReactive Programming in Java 8 with Rx-Java
Reactive Programming in Java 8 with Rx-Java
 
An intro to Kubernetes operators
An intro to Kubernetes operatorsAn intro to Kubernetes operators
An intro to Kubernetes operators
 
.Net Core
.Net Core.Net Core
.Net Core
 
Build Your Own Angular Component Library
Build Your Own Angular Component LibraryBuild Your Own Angular Component Library
Build Your Own Angular Component Library
 
Kubernetes
KubernetesKubernetes
Kubernetes
 
Code quality for Terraform
Code quality for TerraformCode quality for Terraform
Code quality for Terraform
 
Capabilities for Resources and Effects
Capabilities for Resources and EffectsCapabilities for Resources and Effects
Capabilities for Resources and Effects
 
Devops - Microservice and Kubernetes
Devops - Microservice and KubernetesDevops - Microservice and Kubernetes
Devops - Microservice and Kubernetes
 
Building .NET Microservices
Building .NET MicroservicesBuilding .NET Microservices
Building .NET Microservices
 
Azure Interview Questions And Answers | Azure Tutorial For Beginners | Azure ...
Azure Interview Questions And Answers | Azure Tutorial For Beginners | Azure ...Azure Interview Questions And Answers | Azure Tutorial For Beginners | Azure ...
Azure Interview Questions And Answers | Azure Tutorial For Beginners | Azure ...
 
The New JavaScript: ES6
The New JavaScript: ES6The New JavaScript: ES6
The New JavaScript: ES6
 
Middleware in Asp.Net Core
Middleware in Asp.Net CoreMiddleware in Asp.Net Core
Middleware in Asp.Net Core
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooks
 
Introducing Amazon EKS Anywhere On Apache CloudStack
Introducing Amazon EKS Anywhere On Apache CloudStackIntroducing Amazon EKS Anywhere On Apache CloudStack
Introducing Amazon EKS Anywhere On Apache CloudStack
 

Similar to Javascript ES6 generators

Web Optimization Summit: Coding for Performance
Web Optimization Summit: Coding for PerformanceWeb Optimization Summit: Coding for Performance
Web Optimization Summit: Coding for Performance
johndaviddalton
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Seri Moth
 
EcmaScript 6
EcmaScript 6 EcmaScript 6
EcmaScript 6
Manoj Kumar
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
Stoyan Stefanov
 
Adding ES6 to Your Developer Toolbox
Adding ES6 to Your Developer ToolboxAdding ES6 to Your Developer Toolbox
Adding ES6 to Your Developer Toolbox
Jeff Strauss
 
04 Advanced Javascript
04 Advanced Javascript04 Advanced Javascript
04 Advanced Javascript
crgwbr
 
ES6: The future is now
ES6: The future is nowES6: The future is now
ES6: The future is now
Sebastiano Armeli
 
Intro to Advanced JavaScript
Intro to Advanced JavaScriptIntro to Advanced JavaScript
Intro to Advanced JavaScript
ryanstout
 
The redux saga begins
The redux saga beginsThe redux saga begins
The redux saga begins
Daniel Franz
 
JSLab. Домников Виталий. "ES6 генераторы и Koa.js"
JSLab. Домников Виталий. "ES6 генераторы и Koa.js"JSLab. Домников Виталий. "ES6 генераторы и Koa.js"
JSLab. Домников Виталий. "ES6 генераторы и Koa.js"
GeeksLab Odessa
 
Fat Arrow (ES6)
Fat Arrow (ES6)Fat Arrow (ES6)
Fat Arrow (ES6)
Ryan Ewing
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
Manoj Kumar
 
ES6 generators
ES6 generatorsES6 generators
ES6 generators
Steven Foote
 
No excuses, switch to kotlin
No excuses, switch to kotlinNo excuses, switch to kotlin
No excuses, switch to kotlin
Thijs Suijten
 
Javascript essentials
Javascript essentialsJavascript essentials
Javascript essentials
Bedis ElAchèche
 
01 Introduction to Kotlin - Programming in Kotlin.pptx
01 Introduction to Kotlin - Programming in Kotlin.pptx01 Introduction to Kotlin - Programming in Kotlin.pptx
01 Introduction to Kotlin - Programming in Kotlin.pptx
IvanZawPhyo
 
Introduction to Kotlin.pptx
Introduction to Kotlin.pptxIntroduction to Kotlin.pptx
Introduction to Kotlin.pptx
AzharFauzan9
 
Functional Programming in PHP
Functional Programming in PHPFunctional Programming in PHP
Functional Programming in PHP
pwmosquito
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
Ryan McGeary
 

Similar to Javascript ES6 generators (20)

Web Optimization Summit: Coding for Performance
Web Optimization Summit: Coding for PerformanceWeb Optimization Summit: Coding for Performance
Web Optimization Summit: Coding for Performance
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02
 
EcmaScript 6
EcmaScript 6 EcmaScript 6
EcmaScript 6
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
 
Adding ES6 to Your Developer Toolbox
Adding ES6 to Your Developer ToolboxAdding ES6 to Your Developer Toolbox
Adding ES6 to Your Developer Toolbox
 
04 Advanced Javascript
04 Advanced Javascript04 Advanced Javascript
04 Advanced Javascript
 
ES6: The future is now
ES6: The future is nowES6: The future is now
ES6: The future is now
 
Intro to Advanced JavaScript
Intro to Advanced JavaScriptIntro to Advanced JavaScript
Intro to Advanced JavaScript
 
The redux saga begins
The redux saga beginsThe redux saga begins
The redux saga begins
 
JSLab. Домников Виталий. "ES6 генераторы и Koa.js"
JSLab. Домников Виталий. "ES6 генераторы и Koa.js"JSLab. Домников Виталий. "ES6 генераторы и Koa.js"
JSLab. Домников Виталий. "ES6 генераторы и Koa.js"
 
Fat Arrow (ES6)
Fat Arrow (ES6)Fat Arrow (ES6)
Fat Arrow (ES6)
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
 
ES6 generators
ES6 generatorsES6 generators
ES6 generators
 
No excuses, switch to kotlin
No excuses, switch to kotlinNo excuses, switch to kotlin
No excuses, switch to kotlin
 
Javascript essentials
Javascript essentialsJavascript essentials
Javascript essentials
 
01 Introduction to Kotlin - Programming in Kotlin.pptx
01 Introduction to Kotlin - Programming in Kotlin.pptx01 Introduction to Kotlin - Programming in Kotlin.pptx
01 Introduction to Kotlin - Programming in Kotlin.pptx
 
Introduction to Kotlin.pptx
Introduction to Kotlin.pptxIntroduction to Kotlin.pptx
Introduction to Kotlin.pptx
 
Functional Programming in PHP
Functional Programming in PHPFunctional Programming in PHP
Functional Programming in PHP
 
Short intro to ECMAScript
Short intro to ECMAScriptShort intro to ECMAScript
Short intro to ECMAScript
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
 

More from Ramesh Nair

solUI Introduction (2019)
solUI Introduction (2019)solUI Introduction (2019)
solUI Introduction (2019)
Ramesh Nair
 
Kickback - incentivizing event attendance through crypto economics
Kickback - incentivizing event attendance through crypto economicsKickback - incentivizing event attendance through crypto economics
Kickback - incentivizing event attendance through crypto economics
Ramesh Nair
 
Introduction to Blockchains
Introduction to BlockchainsIntroduction to Blockchains
Introduction to Blockchains
Ramesh Nair
 
Introduction to PhoneGap
Introduction to PhoneGapIntroduction to PhoneGap
Introduction to PhoneGap
Ramesh Nair
 
Introduction to Dart
Introduction to DartIntroduction to Dart
Introduction to Dart
Ramesh Nair
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
Ramesh Nair
 
Javascript Update May 2013
Javascript Update May 2013Javascript Update May 2013
Javascript Update May 2013
Ramesh Nair
 

More from Ramesh Nair (7)

solUI Introduction (2019)
solUI Introduction (2019)solUI Introduction (2019)
solUI Introduction (2019)
 
Kickback - incentivizing event attendance through crypto economics
Kickback - incentivizing event attendance through crypto economicsKickback - incentivizing event attendance through crypto economics
Kickback - incentivizing event attendance through crypto economics
 
Introduction to Blockchains
Introduction to BlockchainsIntroduction to Blockchains
Introduction to Blockchains
 
Introduction to PhoneGap
Introduction to PhoneGapIntroduction to PhoneGap
Introduction to PhoneGap
 
Introduction to Dart
Introduction to DartIntroduction to Dart
Introduction to Dart
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
 
Javascript Update May 2013
Javascript Update May 2013Javascript Update May 2013
Javascript Update May 2013
 

Recently uploaded

The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 

Recently uploaded (20)

The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 

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 ?