SlideShare a Scribd company logo
ES6 Generators
Feel the *power
Avoid callback inception
Avoid callback inception
$el.on('click', function(evt) {
$.ajax('/vsearch/pj', function(data) {
dust.render('tl/shared/person', data, function
(err, out) {
$el.html(out);
// Please, make it stop!
})
})
});
Example
> function *hoover() {
console.log('Preparing to yield "Boulder"');
yield 'Boulder';
console.log('All done yielding');
}
> let iter = hoover();
// Nothing happens...
> iter.next();
'Preparing to yield "Boulder"'
Object {value: "Boulder", done: false}
> iter.next();
'All done yielding'
Object {value: undefined, done: true}
Iterators
Behind every Generator is a great Iterator
next()
next()
All an object needs to be an iterator is a next* method, which
returns an object with a value property and a done property.
* Iterators generally also include a throw method for throwing errors.
for … of
function *hoover() {
console.log('Preparing to yield "Boulder"');
yield 'Boulder';
console.log('All done yielding');
}
for (let x of hoover()) {
console.log(`x is ${x}`);
}
// Output:
/*
Preparing to yield "Boulder"
x is Boulder
All done yielding
*/
Iterables
● Arrays
● Maps
● Sets
Iterables
let vals = ['a', 'b', 'c'];
for (let x of vals) {
console.log(`x is ${x}`);
}
// Output:
/*
'a'
'b'
'c'
*/
// Python lovers rejoice
Yield
Yield
Fibonacci Generator
function *fibGenerator() {
let prev1 = 1;
let prev2 = 0;
let current;
yield prev2;
yield prev1;
while (true) {
current = prev1 + prev2;
prev2 = prev1;
prev1 = current;
yield current;
}
}
Using the Fibonacci Generator
var fib = fibGenerator();
console.log(fib.next());
0
console.log(fib.next());
1
console.log(fib.next());
1
console.log(fib.next());
2
console.log(fib.next());
3
console.log(fib.next());
5
Wait for it...
Prompt
We already know how to pause execution in the middle of
a function.
function getName() {
var name = prompt('What's your name?');
return name;
}
But now we can pause execution without freezing the entire
browser.
Wait for it...
Avoid callback inception
$el.on('click', function(evt) {
$.ajax('/vsearch/pj', function(data) {
dust.render('tl/shared/person', data, function
(err, out) {
$el.html(out);
// Please, make it stop!
})
})
});
remember?
yield is the new callback
function *showFeed() {
let data = yield request('/feed');
let dom = yield feedTemplate.render(data);
document.querySelector('#feed-container').appendChild(dom);
}
// To use
runMyGenerator(showFeed);
Behind the Scenes - request
function request(url) {
if (cachedResponses[url]) {
return cachedResponses[url];
} else {
return Promise(function(resolve, reject) {
makeAjaxRequest(url, resolve);
});
}
}
Behind the Scenes - runMyGenerator
function runMyGenerator(gen) {
let iter = gen();
let yielded;
(function iterate(val) {
yielded = iter.next(val);
if (!yielded.done) {
if ('then' in yielded.value) {
// Wait for the promise to resolve before the next iteration
yielded.value.then(iterate);
} else {
// Next
setTimeout(function() {
iterate(val);
}, 0);
}
}
})();
}
Sneak Peak: ES7 Async Functions
async function showFeed(url) {
let data = await request('/feed');
let dom = await feedTemplate.render(data);
document.querySelector('#feed-container').appendChild(dom);
}
showFeed('/feed');
Resources
● David Walsh blog by Kyle Simpson
● Understanding ES6 by Nicholas Zakas

More Related Content

PDF
Javascript ES6 generators
PDF
JSLab. Домников Виталий. "ES6 генераторы и Koa.js"
PDF
EcmaScript 6 - The future is here
PDF
ng-conf 2017: Angular Mischief Maker Slides
PDF
Andrii Orlov "Generators Flexibility in Modern Code"
PDF
Jggug 2010 330 Grails 1.3 観察
PDF
Any event intro
PPTX
Process monitoring in UNIX shell scripting
Javascript ES6 generators
JSLab. Домников Виталий. "ES6 генераторы и Koa.js"
EcmaScript 6 - The future is here
ng-conf 2017: Angular Mischief Maker Slides
Andrii Orlov "Generators Flexibility in Modern Code"
Jggug 2010 330 Grails 1.3 観察
Any event intro
Process monitoring in UNIX shell scripting

What's hot (20)

PPTX
Perl: Coro asynchronous
KEY
Clojure入門
PDF
Intro to Systems Orchestration with MCollective
PPTX
C to perl binding
PPTX
JavaScript Sprachraum
PDF
ES6 - Level up your JavaScript Skills
KEY
XpUg Coding Dojo: KataYahtzee in Ocp way
PDF
GPars For Beginners
KEY
Agile Iphone Development
PPTX
Cis 216 – shell scripting
PDF
第4回 g* ワークショップ はじめてみよう! Grailsプラグイン
PDF
Absolute Beginners Guide to Puppet Through Types - PuppetConf 2014
PPTX
Avoiding callback hell in Node js using promises
PDF
Python postgre sql a wonderful wedding
PDF
"PostgreSQL and Python" Lightning Talk @EuroPython2014
PDF
How to stand on the shoulders of giants
PDF
ES2015 (ES6) Overview
PDF
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
PDF
第3回Grails/Groovy勉強会名古屋「Grails名古屋座談会」
PDF
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
Perl: Coro asynchronous
Clojure入門
Intro to Systems Orchestration with MCollective
C to perl binding
JavaScript Sprachraum
ES6 - Level up your JavaScript Skills
XpUg Coding Dojo: KataYahtzee in Ocp way
GPars For Beginners
Agile Iphone Development
Cis 216 – shell scripting
第4回 g* ワークショップ はじめてみよう! Grailsプラグイン
Absolute Beginners Guide to Puppet Through Types - PuppetConf 2014
Avoiding callback hell in Node js using promises
Python postgre sql a wonderful wedding
"PostgreSQL and Python" Lightning Talk @EuroPython2014
How to stand on the shoulders of giants
ES2015 (ES6) Overview
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
第3回Grails/Groovy勉強会名古屋「Grails名古屋座談会」
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
Ad

Similar to ES6 generators (20)

PDF
Beyond the Callback: Yield Control with Javascript Generators
PDF
ES6: The Awesome Parts
PDF
The Evolution of Async-Programming (SD 2.0, JavaScript)
PPTX
Iterable, iterator, generator by gaurav khurana
PDF
function* - ES6, generators, and all that (JSRomandie meetup, February 2014)
PPTX
Async Frontiers
PDF
Exploring ES6
PDF
Asynchronous Programming with JavaScript
PDF
Principles of the Play framework
PDF
Promises generatorscallbacks
PDF
Event driven javascript
PDF
Event driven javascript
PDF
ES6 - Next Generation Javascript
PPTX
Iterators & Generators in ECMAScript 6.0
PPTX
Single Page Applications with AngularJS 2.0
PDF
How to actually use promises - Jakob Mattsson, FishBrain
PPTX
ECMAScript 2015: my favourite parts
PDF
Writing testable js [by Ted Piotrowski]
PDF
Generating Power with Yield
PDF
Testing web APIs
Beyond the Callback: Yield Control with Javascript Generators
ES6: The Awesome Parts
The Evolution of Async-Programming (SD 2.0, JavaScript)
Iterable, iterator, generator by gaurav khurana
function* - ES6, generators, and all that (JSRomandie meetup, February 2014)
Async Frontiers
Exploring ES6
Asynchronous Programming with JavaScript
Principles of the Play framework
Promises generatorscallbacks
Event driven javascript
Event driven javascript
ES6 - Next Generation Javascript
Iterators & Generators in ECMAScript 6.0
Single Page Applications with AngularJS 2.0
How to actually use promises - Jakob Mattsson, FishBrain
ECMAScript 2015: my favourite parts
Writing testable js [by Ted Piotrowski]
Generating Power with Yield
Testing web APIs
Ad

Recently uploaded (20)

PPTX
Big Data Technologies - Introduction.pptx
PDF
Machine learning based COVID-19 study performance prediction
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
cuic standard and advanced reporting.pdf
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
Cloud computing and distributed systems.
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Empathic Computing: Creating Shared Understanding
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Approach and Philosophy of On baking technology
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
KodekX | Application Modernization Development
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Big Data Technologies - Introduction.pptx
Machine learning based COVID-19 study performance prediction
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
cuic standard and advanced reporting.pdf
Per capita expenditure prediction using model stacking based on satellite ima...
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Cloud computing and distributed systems.
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Advanced methodologies resolving dimensionality complications for autism neur...
NewMind AI Weekly Chronicles - August'25 Week I
Empathic Computing: Creating Shared Understanding
Building Integrated photovoltaic BIPV_UPV.pdf
Approach and Philosophy of On baking technology
Mobile App Security Testing_ A Comprehensive Guide.pdf
Chapter 3 Spatial Domain Image Processing.pdf
KodekX | Application Modernization Development
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Reach Out and Touch Someone: Haptics and Empathic Computing
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy

ES6 generators

  • 4. Avoid callback inception $el.on('click', function(evt) { $.ajax('/vsearch/pj', function(data) { dust.render('tl/shared/person', data, function (err, out) { $el.html(out); // Please, make it stop! }) }) });
  • 5. Example > function *hoover() { console.log('Preparing to yield "Boulder"'); yield 'Boulder'; console.log('All done yielding'); } > let iter = hoover(); // Nothing happens... > iter.next(); 'Preparing to yield "Boulder"' Object {value: "Boulder", done: false} > iter.next(); 'All done yielding' Object {value: undefined, done: true}
  • 6. Iterators Behind every Generator is a great Iterator
  • 8. next() All an object needs to be an iterator is a next* method, which returns an object with a value property and a done property. * Iterators generally also include a throw method for throwing errors.
  • 9. for … of function *hoover() { console.log('Preparing to yield "Boulder"'); yield 'Boulder'; console.log('All done yielding'); } for (let x of hoover()) { console.log(`x is ${x}`); } // Output: /* Preparing to yield "Boulder" x is Boulder All done yielding */
  • 11. Iterables let vals = ['a', 'b', 'c']; for (let x of vals) { console.log(`x is ${x}`); } // Output: /* 'a' 'b' 'c' */ // Python lovers rejoice
  • 12. Yield
  • 13. Yield
  • 14. Fibonacci Generator function *fibGenerator() { let prev1 = 1; let prev2 = 0; let current; yield prev2; yield prev1; while (true) { current = prev1 + prev2; prev2 = prev1; prev1 = current; yield current; } }
  • 15. Using the Fibonacci Generator var fib = fibGenerator(); console.log(fib.next()); 0 console.log(fib.next()); 1 console.log(fib.next()); 1 console.log(fib.next()); 2 console.log(fib.next()); 3 console.log(fib.next()); 5
  • 17. Prompt We already know how to pause execution in the middle of a function. function getName() { var name = prompt('What's your name?'); return name; } But now we can pause execution without freezing the entire browser.
  • 19. Avoid callback inception $el.on('click', function(evt) { $.ajax('/vsearch/pj', function(data) { dust.render('tl/shared/person', data, function (err, out) { $el.html(out); // Please, make it stop! }) }) }); remember?
  • 20. yield is the new callback function *showFeed() { let data = yield request('/feed'); let dom = yield feedTemplate.render(data); document.querySelector('#feed-container').appendChild(dom); } // To use runMyGenerator(showFeed);
  • 21. Behind the Scenes - request function request(url) { if (cachedResponses[url]) { return cachedResponses[url]; } else { return Promise(function(resolve, reject) { makeAjaxRequest(url, resolve); }); } }
  • 22. Behind the Scenes - runMyGenerator function runMyGenerator(gen) { let iter = gen(); let yielded; (function iterate(val) { yielded = iter.next(val); if (!yielded.done) { if ('then' in yielded.value) { // Wait for the promise to resolve before the next iteration yielded.value.then(iterate); } else { // Next setTimeout(function() { iterate(val); }, 0); } } })(); }
  • 23. Sneak Peak: ES7 Async Functions async function showFeed(url) { let data = await request('/feed'); let dom = await feedTemplate.render(data); document.querySelector('#feed-container').appendChild(dom); } showFeed('/feed');
  • 24. Resources ● David Walsh blog by Kyle Simpson ● Understanding ES6 by Nicholas Zakas