SlideShare a Scribd company logo
www.luxoft.com
Generators Flexibility in Modern Code
Andrii Orlov
www.luxoft.com
ES6 introduced a new way of working with
functions and iterators in the form of Generators
(or generator functions).
A generator is a function that can stop
midway and then continue from where it
stopped.
In short, a generator appears to be a function
but it behaves like an iterator.
What is a generator?
www.luxoft.com
Simple generator function
function* gen() {
yield 1
yield 2
yield 3
return 4
}
const generator = gen()
generator.next() // {value: 1, done: false}
generator.next() // {value: 2, done: false}
generator.next() // {value: 3, done: false}
generator.next() // {value: 4, done: true}
generator.next() // {value: undefined, done: true}
www.luxoft.com
Function !== Function*
www.luxoft.com
ITERATORS
(data producers)
OBSERVERS
(data consumers)
COROUTINES
(data producers
and consumers)
For-of loops,
spread operator
Observer pattern Cooperatively
multitasked tasks
Roles generators can play
www.luxoft.com
What is an iterator?
interface iteratorResult {
done: boolean,
value: any
}
Iterator is a way to pull data from a data structure on one-at-a-time fashion, it needs to
implement the iterator interface (which has three methods - next(), return() and
throw()).
An iteratorResult that returns from the iterator next() method needs to follow this
interface:
So each time we call next() on an iterator we should get {value: the current
iteration value, done: false/true}
www.luxoft.com
Generator as iterator
function* gen() {
yield 1
yield 2
yield 3
return 4
}
const generator = gen()
for(let value of generator) {
console.log(value); // 1, 2, 3
}
const spreadValues = […generator] // [1, 2, 3]
www.luxoft.com
Generator as observer
function createObserver(iterator) {
return {
next(value) { iterator.next(value) },
error(err) { iterator.throw(err) },
complete() { iterator.return() }
}
}
function* observerGenerator() {
try {
while(true) {
let value = yield
console.log(`next -> ${value}`)
}
} catch (err) {
console.log('error')
}
console.log('completed')
}
function observable(observer) {
for(let i = 0; i <= 10; i++) {
observer.next(i)
}
observer.error()
observer.complete()
}
observable(
createObserver(
observerGenerator()
)
)
Observer Observable
www.luxoft.com
Generators as coroutines. “CO” library
import co from 'co'
const fetchJSON = co.wrap(function* (url) {
try {
let request = yield fetch(url)
let text = yield request.text()
return JSON.parse(text)
}
catch (error) {
console.log(`ERROR: ${error.stack}`)
}
})
www.luxoft.com
Generator + Promise = Async/await ???
www.luxoft.com
Async/await vs generators
async function fetchJSON(url) {
try {
let request = await fetch(url)
let text = await request.text()
return JSON.parse(text)
}
catch (error) {
console.log(`ERROR: ${error.stack}`)
}
}
import co from 'co'
const fetchJSON = co.wrap(function* (url) {
try {
let request = yield fetch(url)
let text = yield request.text()
return JSON.parse(text)
}
catch (error) {
console.log(`ERROR: ${error.stack}`)
}
})
Async/await Generators
www.luxoft.com
Thank you!

More Related Content

PDF
ES6 generators
PDF
Javascript ES6 generators
KEY
Agile Iphone Development
KEY
XpUg Coding Dojo: KataYahtzee in Ocp way
PPT
Class ‘increment’
PDF
PyCon lightning talk on my Toro module for Tornado
PDF
2016 gunma.web games-and-asm.js
PDF
Python meetup: coroutines, event loops, and non-blocking I/O
ES6 generators
Javascript ES6 generators
Agile Iphone Development
XpUg Coding Dojo: KataYahtzee in Ocp way
Class ‘increment’
PyCon lightning talk on my Toro module for Tornado
2016 gunma.web games-and-asm.js
Python meetup: coroutines, event loops, and non-blocking I/O

What's hot (20)

PDF
20151224-games
PDF
How to instantiate any view controller for free
KEY
Object-Oriented Javascript
PDF
Introduction to ES2015
PDF
UI 모듈화로 워라밸 지키기
PDF
Of Harmony and Stinginess: Applicative, Monad, and iterative library design
PDF
Sequential Async Call
PPTX
Voldemort collections library
PPTX
No More Deadlocks; Asynchronous Programming in .NET
PPTX
Asynchronous programming
DOCX
7th lab
PDF
C++ question 6 || solution of Programming Problem
PDF
Python Coroutines, Present and Future
PPTX
Promises, promises, and then observables
PPTX
Dts x dicoding #2 memulai pemrograman kotlin
PDF
ESCMAScript 6: Get Ready For The Future. Now
PDF
EcmaScript 6 - The future is here
PDF
Jggug 2010 330 Grails 1.3 観察
PDF
State managment in a world of hooks
KEY
Python Yield
20151224-games
How to instantiate any view controller for free
Object-Oriented Javascript
Introduction to ES2015
UI 모듈화로 워라밸 지키기
Of Harmony and Stinginess: Applicative, Monad, and iterative library design
Sequential Async Call
Voldemort collections library
No More Deadlocks; Asynchronous Programming in .NET
Asynchronous programming
7th lab
C++ question 6 || solution of Programming Problem
Python Coroutines, Present and Future
Promises, promises, and then observables
Dts x dicoding #2 memulai pemrograman kotlin
ESCMAScript 6: Get Ready For The Future. Now
EcmaScript 6 - The future is here
Jggug 2010 330 Grails 1.3 観察
State managment in a world of hooks
Python Yield
Ad

Similar to Andrii Orlov "Generators Flexibility in Modern Code" (20)

PPTX
Iterable, iterator, generator by gaurav khurana
PDF
function* - ES6, generators, and all that (JSRomandie meetup, February 2014)
PDF
JavaScript Iteration Protocols - Workshop NodeConf EU 2022
PPTX
python ppt.pptx
PPTX
Async Frontiers
PDF
Beyond the Callback: Yield Control with Javascript Generators
PPTX
Iterarators and generators in python
ODP
ES6 PPT FOR 2016
PDF
Javascript: repetita iuvant
PPTX
ECMAScript 2015: my favourite parts
PDF
The Evolution of Async-Programming (SD 2.0, JavaScript)
PPTX
08-Iterators-and-Generators.pptx
PDF
Infinum iOS Talks #4 - Making our VIPER more reactive
PDF
Exploring ES6
PDF
Promises generatorscallbacks
PPTX
The redux saga begins
PPTX
Process control nodejs
PPTX
Generators-in-Python-for-Developers.pptx
PPTX
Single Page Applications with AngularJS 2.0
Iterable, iterator, generator by gaurav khurana
function* - ES6, generators, and all that (JSRomandie meetup, February 2014)
JavaScript Iteration Protocols - Workshop NodeConf EU 2022
python ppt.pptx
Async Frontiers
Beyond the Callback: Yield Control with Javascript Generators
Iterarators and generators in python
ES6 PPT FOR 2016
Javascript: repetita iuvant
ECMAScript 2015: my favourite parts
The Evolution of Async-Programming (SD 2.0, JavaScript)
08-Iterators-and-Generators.pptx
Infinum iOS Talks #4 - Making our VIPER more reactive
Exploring ES6
Promises generatorscallbacks
The redux saga begins
Process control nodejs
Generators-in-Python-for-Developers.pptx
Single Page Applications with AngularJS 2.0
Ad

More from LogeekNightUkraine (20)

PPTX
Face recognition with c++
PPTX
C++20 features
PPTX
Autonomous driving on your developer pc. technologies, approaches, future
PDF
Orkhan Gasimov "High Performance System Design"
PPTX
Vitalii Korzh "Managed Workflows or How to Master Data"
PDF
Yevhen Tatarynov "From POC to High-Performance .NET applications"
PDF
Oleksii Kuchuk "Reading gauge values with open cv imgproc"
PDF
Oleksandr Kutsan "Using katai struct to describe the process of working with ...
PDF
Pavlo Zhdanov "Mastering solid and base principles for software design"
PDF
Serhii Zemlianyi "Error Retries with Exponential Backoff Using RabbitMQ"
PDF
Iurii Antykhovych "Java and performance tools and toys"
PDF
Eugene Bova "Dapr (Distributed Application Runtime) in a Microservices Archit...
PPTX
Aleksandr Kutsan "Managing Dependencies in C++"
PDF
Yevhen Tatarynov "My .NET Application Allocates too Much Memory. What Can I Do?"
PDF
Alexandr Golyak, Nikolay Chertkov "Automotive Testing vs Test Automatio"
PPTX
Michal Kordas "Docker: Good, Bad or Both"
PPTX
Kolomiyets Dmytro "Dealing with Multiple Caches, When Developing Microservices"
PPTX
Shestakov Illia "The Sandbox Theory"
PPTX
Dmytro Kochergin “Autotest with CYPRESS”
PPTX
Ivan Dryzhyruk “Ducks Don’t Like Bugs”
Face recognition with c++
C++20 features
Autonomous driving on your developer pc. technologies, approaches, future
Orkhan Gasimov "High Performance System Design"
Vitalii Korzh "Managed Workflows or How to Master Data"
Yevhen Tatarynov "From POC to High-Performance .NET applications"
Oleksii Kuchuk "Reading gauge values with open cv imgproc"
Oleksandr Kutsan "Using katai struct to describe the process of working with ...
Pavlo Zhdanov "Mastering solid and base principles for software design"
Serhii Zemlianyi "Error Retries with Exponential Backoff Using RabbitMQ"
Iurii Antykhovych "Java and performance tools and toys"
Eugene Bova "Dapr (Distributed Application Runtime) in a Microservices Archit...
Aleksandr Kutsan "Managing Dependencies in C++"
Yevhen Tatarynov "My .NET Application Allocates too Much Memory. What Can I Do?"
Alexandr Golyak, Nikolay Chertkov "Automotive Testing vs Test Automatio"
Michal Kordas "Docker: Good, Bad or Both"
Kolomiyets Dmytro "Dealing with Multiple Caches, When Developing Microservices"
Shestakov Illia "The Sandbox Theory"
Dmytro Kochergin “Autotest with CYPRESS”
Ivan Dryzhyruk “Ducks Don’t Like Bugs”

Recently uploaded (20)

PDF
MIND Revenue Release Quarter 2 2025 Press Release
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
Network Security Unit 5.pdf for BCA BBA.
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PPTX
Big Data Technologies - Introduction.pptx
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
Spectroscopy.pptx food analysis technology
PDF
Electronic commerce courselecture one. Pdf
PPT
Teaching material agriculture food technology
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
cuic standard and advanced reporting.pdf
MIND Revenue Release Quarter 2 2025 Press Release
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Network Security Unit 5.pdf for BCA BBA.
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
“AI and Expert System Decision Support & Business Intelligence Systems”
Reach Out and Touch Someone: Haptics and Empathic Computing
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Big Data Technologies - Introduction.pptx
Digital-Transformation-Roadmap-for-Companies.pptx
Spectroscopy.pptx food analysis technology
Electronic commerce courselecture one. Pdf
Teaching material agriculture food technology
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Building Integrated photovoltaic BIPV_UPV.pdf
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
cuic standard and advanced reporting.pdf

Andrii Orlov "Generators Flexibility in Modern Code"

  • 1. www.luxoft.com Generators Flexibility in Modern Code Andrii Orlov
  • 2. www.luxoft.com ES6 introduced a new way of working with functions and iterators in the form of Generators (or generator functions). A generator is a function that can stop midway and then continue from where it stopped. In short, a generator appears to be a function but it behaves like an iterator. What is a generator?
  • 3. www.luxoft.com Simple generator function function* gen() { yield 1 yield 2 yield 3 return 4 } const generator = gen() generator.next() // {value: 1, done: false} generator.next() // {value: 2, done: false} generator.next() // {value: 3, done: false} generator.next() // {value: 4, done: true} generator.next() // {value: undefined, done: true}
  • 5. www.luxoft.com ITERATORS (data producers) OBSERVERS (data consumers) COROUTINES (data producers and consumers) For-of loops, spread operator Observer pattern Cooperatively multitasked tasks Roles generators can play
  • 6. www.luxoft.com What is an iterator? interface iteratorResult { done: boolean, value: any } Iterator is a way to pull data from a data structure on one-at-a-time fashion, it needs to implement the iterator interface (which has three methods - next(), return() and throw()). An iteratorResult that returns from the iterator next() method needs to follow this interface: So each time we call next() on an iterator we should get {value: the current iteration value, done: false/true}
  • 7. www.luxoft.com Generator as iterator function* gen() { yield 1 yield 2 yield 3 return 4 } const generator = gen() for(let value of generator) { console.log(value); // 1, 2, 3 } const spreadValues = […generator] // [1, 2, 3]
  • 8. www.luxoft.com Generator as observer function createObserver(iterator) { return { next(value) { iterator.next(value) }, error(err) { iterator.throw(err) }, complete() { iterator.return() } } } function* observerGenerator() { try { while(true) { let value = yield console.log(`next -> ${value}`) } } catch (err) { console.log('error') } console.log('completed') } function observable(observer) { for(let i = 0; i <= 10; i++) { observer.next(i) } observer.error() observer.complete() } observable( createObserver( observerGenerator() ) ) Observer Observable
  • 9. www.luxoft.com Generators as coroutines. “CO” library import co from 'co' const fetchJSON = co.wrap(function* (url) { try { let request = yield fetch(url) let text = yield request.text() return JSON.parse(text) } catch (error) { console.log(`ERROR: ${error.stack}`) } })
  • 11. www.luxoft.com Async/await vs generators async function fetchJSON(url) { try { let request = await fetch(url) let text = await request.text() return JSON.parse(text) } catch (error) { console.log(`ERROR: ${error.stack}`) } } import co from 'co' const fetchJSON = co.wrap(function* (url) { try { let request = yield fetch(url) let text = yield request.text() return JSON.parse(text) } catch (error) { console.log(`ERROR: ${error.stack}`) } }) Async/await Generators