SlideShare a Scribd company logo
1 of 27
Dead-Simple Async
Control Flow with
Coroutines
by Travis Kaufman (@traviskaufman)
github.com/traviskaufman/co-talk-examples
Outline
Define the problem
Async control flow in NodeJS
Present the solution
Coroutines (surprise!)
Explore the implementation
How coroutines work under the hood
Coroutine libraries
Start using them in your apps today!
(time permitting) Advanced usage
Sample code showing where coroutines really shine
source: https://onlivetest.files.wordpress.com/2014/06/pyramid-of-doom.jpg
The Problem
Callbacks are UNINTUITIVE
source: http://i.imgur.com/DEg3cPZ.png
Callbacks are UNINTUITIVE
Simple Program: Get GH Username, print out 10 most recently pushed repos
https://github.com/traviskaufman/co-talk-examples/blob/master/01-raw-callbacks.js
Callbacks are UNINTUITIVE
Simple Program: Get GH Username, print out 10 most recently pushed repos
https://github.com/traviskaufman/co-talk-examples/blob/master/01-raw-callbacks.js
Code duplication
Callbacks are UNINTUITIVE
Simple Program: Get GH Username, print out 10 most recently pushed repos
https://github.com/traviskaufman/co-talk-examples/blob/master/01-raw-callbacks.js
Code duplication
“Diagonal Development” / Pyramid of Doom / Callback Hell / etc
Callbacks are UNINTUITIVE
Simple Program: Get GH Username, print out 10 most recently pushed repos
https://github.com/traviskaufman/co-talk-examples/blob/master/01-raw-callbacks.js
Code duplication
Refactoring callbacks means
jumping around code to see logical
flow of execution :((
“Diagonal Development” / Pyramid of Doom / Callback Hell / etc
https://github.com/traviskaufman/co-talk-examples/blob/master/02-async-lib-callbacks.js
Callbacks are UNINTUITIVE
The “solution”: use a library (e.g. caolan/async, a.k.a. the jQuery of NodeJS)
Callbacks are UNINTUITIVE
The “solution”: use a library (e.g. caolan/async, a.k.a. the jQuery of NodeJS)
Only have to handle this in one place! :D
https://github.com/traviskaufman/co-talk-examples/blob/master/02-async-lib-callbacks.js
Callbacks are UNINTUITIVE
The “solution”: use a library (e.g. caolan/async, a.k.a. the jQuery of NodeJS)
Need to be familiar with “async.waterfall”
API Change to accommodate lib usage?
Only have to handle this in one place! :D
https://github.com/traviskaufman/co-talk-examples/blob/master/02-async-lib-callbacks.js
Promises to the Rescue!
https://github.com/traviskaufman/co-talk-examples/blob/master/03-raw-promises.js
No triangles/pyramids/hells/doom/etc.
Error handling separated from general logic
Promises to the Rescue! but...
https://github.com/traviskaufman/co-talk-examples/blob/master/03-raw-promises.js
No triangles/pyramids/hells/doom/etc.
Error handling separated from general logic
API Weirdness still...
Still requires handler functions for promise settling
Can We Do Better?
Readability of synchronous code
I/O Efficiency of Asynchronous Code
YES! Introducing Coroutines
https://github.com/traviskaufman/co-talk-examples/blob/master/04-co-promises.js
YES! Introducing Coroutines
● coroutine(gen: GeneratorFunction) => Promise
● generator function yields Promises
● values from resolved promises are assigned
● errors from rejected promises are thrown within generator
○ note: could use try/catch inside generator to call handleError()
● Returns Promise for easy interop with other async code
● Best of both worlds! Readability/Intuitiveness + Efficiency/Non-blocking I/O
https://github.com/traviskaufman/co-talk-examples/blob/master/04-co-promises.js
F*CK YEAH
source:
http://3.bp.blogspot.com/-
IYYJ3t1g8hA/ToJtrJegK4I/AA
AAAAAAAUg/qTG1Jh50PsY/s
1600/1264744915828.jpg
Coroutines = “Cooperative Routines”
Cooperative threads are
responsible for explicitly telling
executor when they should be
suspended
Differs from preemptive threads
which rely on executor to
suspend/resume them
Reference (Java-based):
http://www.cafeaulait.org/course/
week11/32.html
https://www.cs.mtu.edu/~shene/NSF-3/e-Book/FUNDAMENTALS/thread-yield.jpg
Coroutines = “Cooperative Routines”
Generators provide cooperation
through the yield keyword
Explicitly tells IO-Loop (uv,
etc.) to suspend execution
Promises provide the routines
Scheduled and run
asynchronously by IO-Loop
Generators + Promises =
Cooperation + Routines =
Coroutines!
https://www.cs.mtu.edu/~shene/NSF-3/e-Book/FUNDAMENTALS/thread-yield.jpg
yield
new Promise(...)
A Simple Implementation
< 25 SLOC!
Coroutine Libraries: tj/co
My personal favorite
Supports thunks as well as promises
Supports yielding arrays/objects
(Promise.race), as well as generators
(delegation)
https://github.com/tj/co
Coroutine Libraries: mozilla/task.js
Similar to co
Very powerful built-in scheduler
Adds cancellation to promises
Makes coroutines look a lot like thread-based
scheduling
http://taskjs.org/
“But wait, I need ES2015 for this!”
Use babelJS (https://babeljs.io/) to transpile
your code!
Use the --harmony-generators flag with
v0.11+ to enable generators (or just --
harmony)
Check out petkaantonov/bluebird for an
awesome promise polyfill/superset.
Advanced Example: “Retry” with exponential backoff
Advanced Example: DB Cursoring
Additional Resources
MDN reference for generator functions
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*
Awesome Promise tutorial from HTML5Rocks
http://www.html5rocks.com/en/tutorials/es6/promises/
“Promises and Generators: Control Flow Utopia” - Great presentation by Forbes Lindesay
http://pag.forbeslindesay.co.uk/#/
“No Promises: Asynchronous Javascript with only generators”
http://www.2ality.com/2015/03/no-promises.html
Axel Rauschmayer takes it one step further and shows how you can use generators to write
async code without the need for promises. Super interesting stuff!
THANK YOU SO MUCH! :D

More Related Content

What's hot

Google C++ Testing Framework in Visual Studio 2008
Google C++ Testing Framework in Visual Studio 2008Google C++ Testing Framework in Visual Studio 2008
Google C++ Testing Framework in Visual Studio 2008Andrea Francia
 
Functional Reactive Programming on Android
Functional Reactive Programming on AndroidFunctional Reactive Programming on Android
Functional Reactive Programming on AndroidSam Lee
 
Killer R10K Workflow - PuppetConf 2014
Killer R10K Workflow - PuppetConf 2014Killer R10K Workflow - PuppetConf 2014
Killer R10K Workflow - PuppetConf 2014Puppet
 
Introduction to Continous Integration with WordPress
Introduction to Continous Integration with WordPressIntroduction to Continous Integration with WordPress
Introduction to Continous Integration with WordPressSeagyn Davis
 
Scalable Deployment Architectures with TYPO3 Surf, Git and Jenkins
Scalable Deployment Architectures with TYPO3 Surf, Git and JenkinsScalable Deployment Architectures with TYPO3 Surf, Git and Jenkins
Scalable Deployment Architectures with TYPO3 Surf, Git and Jenkinsmhelmich
 
PuppetConf 2016: Docker, Mesos, Kubernetes and...Puppet? Don't Panic! – Deep...
PuppetConf 2016:  Docker, Mesos, Kubernetes and...Puppet? Don't Panic! – Deep...PuppetConf 2016:  Docker, Mesos, Kubernetes and...Puppet? Don't Panic! – Deep...
PuppetConf 2016: Docker, Mesos, Kubernetes and...Puppet? Don't Panic! – Deep...Puppet
 
Continuous Delivery of Puppet Manifests
Continuous Delivery of Puppet ManifestsContinuous Delivery of Puppet Manifests
Continuous Delivery of Puppet ManifestsKris Buytaert
 
Continous Delivering a PHP application
Continous Delivering a PHP applicationContinous Delivering a PHP application
Continous Delivering a PHP applicationJavier López
 
One commit, one release. Continuously delivering a Symfony project.
One commit, one release. Continuously delivering a Symfony project.One commit, one release. Continuously delivering a Symfony project.
One commit, one release. Continuously delivering a Symfony project.Javier López
 
Golang for PHP Developers: Dependency management with Glide
Golang for PHP Developers: Dependency management with GlideGolang for PHP Developers: Dependency management with Glide
Golang for PHP Developers: Dependency management with GlideRichard Tuin
 
Javaone2008 Bof 5101 Groovytesting
Javaone2008 Bof 5101 GroovytestingJavaone2008 Bof 5101 Groovytesting
Javaone2008 Bof 5101 GroovytestingAndres Almiray
 
PuppetConf 2016: Deploying Multi-Tier Windows Applications with Application O...
PuppetConf 2016: Deploying Multi-Tier Windows Applications with Application O...PuppetConf 2016: Deploying Multi-Tier Windows Applications with Application O...
PuppetConf 2016: Deploying Multi-Tier Windows Applications with Application O...Puppet
 
Continuous Delivery of Puppet-Based Infrastructure - PuppetConf 2014
Continuous Delivery of Puppet-Based Infrastructure - PuppetConf 2014Continuous Delivery of Puppet-Based Infrastructure - PuppetConf 2014
Continuous Delivery of Puppet-Based Infrastructure - PuppetConf 2014Puppet
 
Open Source Swift: Up and Running
Open Source Swift: Up and RunningOpen Source Swift: Up and Running
Open Source Swift: Up and RunningCarl Brown
 
"Highlights from Java 10&11 and Future of Java" at Java User Group Bonn 2018 ...
"Highlights from Java 10&11 and Future of Java" at Java User Group Bonn 2018 ..."Highlights from Java 10&11 and Future of Java" at Java User Group Bonn 2018 ...
"Highlights from Java 10&11 and Future of Java" at Java User Group Bonn 2018 ...Vadym Kazulkin
 
Cool JVM Tools to Help You Test
Cool JVM Tools to Help You TestCool JVM Tools to Help You Test
Cool JVM Tools to Help You TestSchalk Cronjé
 
Learning Git with Workflows
Learning Git with WorkflowsLearning Git with Workflows
Learning Git with WorkflowsMosky Liu
 
Let the contribution begin
Let the contribution beginLet the contribution begin
Let the contribution beginSeongJae Park
 

What's hot (20)

Tdd With Groovy
Tdd With GroovyTdd With Groovy
Tdd With Groovy
 
Google C++ Testing Framework in Visual Studio 2008
Google C++ Testing Framework in Visual Studio 2008Google C++ Testing Framework in Visual Studio 2008
Google C++ Testing Framework in Visual Studio 2008
 
Functional Reactive Programming on Android
Functional Reactive Programming on AndroidFunctional Reactive Programming on Android
Functional Reactive Programming on Android
 
Test Driven In Groovy
Test Driven In GroovyTest Driven In Groovy
Test Driven In Groovy
 
Killer R10K Workflow - PuppetConf 2014
Killer R10K Workflow - PuppetConf 2014Killer R10K Workflow - PuppetConf 2014
Killer R10K Workflow - PuppetConf 2014
 
Introduction to Continous Integration with WordPress
Introduction to Continous Integration with WordPressIntroduction to Continous Integration with WordPress
Introduction to Continous Integration with WordPress
 
Scalable Deployment Architectures with TYPO3 Surf, Git and Jenkins
Scalable Deployment Architectures with TYPO3 Surf, Git and JenkinsScalable Deployment Architectures with TYPO3 Surf, Git and Jenkins
Scalable Deployment Architectures with TYPO3 Surf, Git and Jenkins
 
PuppetConf 2016: Docker, Mesos, Kubernetes and...Puppet? Don't Panic! – Deep...
PuppetConf 2016:  Docker, Mesos, Kubernetes and...Puppet? Don't Panic! – Deep...PuppetConf 2016:  Docker, Mesos, Kubernetes and...Puppet? Don't Panic! – Deep...
PuppetConf 2016: Docker, Mesos, Kubernetes and...Puppet? Don't Panic! – Deep...
 
Continuous Delivery of Puppet Manifests
Continuous Delivery of Puppet ManifestsContinuous Delivery of Puppet Manifests
Continuous Delivery of Puppet Manifests
 
Continous Delivering a PHP application
Continous Delivering a PHP applicationContinous Delivering a PHP application
Continous Delivering a PHP application
 
One commit, one release. Continuously delivering a Symfony project.
One commit, one release. Continuously delivering a Symfony project.One commit, one release. Continuously delivering a Symfony project.
One commit, one release. Continuously delivering a Symfony project.
 
Golang for PHP Developers: Dependency management with Glide
Golang for PHP Developers: Dependency management with GlideGolang for PHP Developers: Dependency management with Glide
Golang for PHP Developers: Dependency management with Glide
 
Javaone2008 Bof 5101 Groovytesting
Javaone2008 Bof 5101 GroovytestingJavaone2008 Bof 5101 Groovytesting
Javaone2008 Bof 5101 Groovytesting
 
PuppetConf 2016: Deploying Multi-Tier Windows Applications with Application O...
PuppetConf 2016: Deploying Multi-Tier Windows Applications with Application O...PuppetConf 2016: Deploying Multi-Tier Windows Applications with Application O...
PuppetConf 2016: Deploying Multi-Tier Windows Applications with Application O...
 
Continuous Delivery of Puppet-Based Infrastructure - PuppetConf 2014
Continuous Delivery of Puppet-Based Infrastructure - PuppetConf 2014Continuous Delivery of Puppet-Based Infrastructure - PuppetConf 2014
Continuous Delivery of Puppet-Based Infrastructure - PuppetConf 2014
 
Open Source Swift: Up and Running
Open Source Swift: Up and RunningOpen Source Swift: Up and Running
Open Source Swift: Up and Running
 
"Highlights from Java 10&11 and Future of Java" at Java User Group Bonn 2018 ...
"Highlights from Java 10&11 and Future of Java" at Java User Group Bonn 2018 ..."Highlights from Java 10&11 and Future of Java" at Java User Group Bonn 2018 ...
"Highlights from Java 10&11 and Future of Java" at Java User Group Bonn 2018 ...
 
Cool JVM Tools to Help You Test
Cool JVM Tools to Help You TestCool JVM Tools to Help You Test
Cool JVM Tools to Help You Test
 
Learning Git with Workflows
Learning Git with WorkflowsLearning Git with Workflows
Learning Git with Workflows
 
Let the contribution begin
Let the contribution beginLet the contribution begin
Let the contribution begin
 

Similar to Dead-Simple Async Control Flow with Coroutines

How to Reverse Engineer Web Applications
How to Reverse Engineer Web ApplicationsHow to Reverse Engineer Web Applications
How to Reverse Engineer Web ApplicationsJarrod Overson
 
Lunch and learn as3_frameworks
Lunch and learn as3_frameworksLunch and learn as3_frameworks
Lunch and learn as3_frameworksYuri Visser
 
Release with confidence
Release with confidenceRelease with confidence
Release with confidenceJohn Congdon
 
nullcon 2011 - Reversing MicroSoft patches to reveal vulnerable code
nullcon 2011 - Reversing MicroSoft patches to reveal vulnerable codenullcon 2011 - Reversing MicroSoft patches to reveal vulnerable code
nullcon 2011 - Reversing MicroSoft patches to reveal vulnerable coden|u - The Open Security Community
 
RichFaces - Testing on Mobile Devices
RichFaces - Testing on Mobile DevicesRichFaces - Testing on Mobile Devices
RichFaces - Testing on Mobile DevicesPavol Pitoňák
 
Jump into Squeak - Integrate Squeak projects with Docker & Github
Jump into Squeak - Integrate Squeak projects with Docker & GithubJump into Squeak - Integrate Squeak projects with Docker & Github
Jump into Squeak - Integrate Squeak projects with Docker & Githubhubx
 
From Generator to Fiber the Road to Coroutine in PHP
From Generator to Fiber the Road to Coroutine in PHPFrom Generator to Fiber the Road to Coroutine in PHP
From Generator to Fiber the Road to Coroutine in PHPAlbert Chen
 
Team Development & Continuous Integration on the Salesforce Platform
Team Development & Continuous Integration on the Salesforce PlatformTeam Development & Continuous Integration on the Salesforce Platform
Team Development & Continuous Integration on the Salesforce PlatformCarlos Ramirez Martinez-Eiroa
 
Fundamentals of programming finals.ajang
Fundamentals of programming finals.ajangFundamentals of programming finals.ajang
Fundamentals of programming finals.ajangJaricka Angelyd Marquez
 
The Hitchhiker's Guide to Faster Builds. Viktor Kirilov. CoreHard Spring 2019
The Hitchhiker's Guide to Faster Builds. Viktor Kirilov. CoreHard Spring 2019The Hitchhiker's Guide to Faster Builds. Viktor Kirilov. CoreHard Spring 2019
The Hitchhiker's Guide to Faster Builds. Viktor Kirilov. CoreHard Spring 2019corehard_by
 
Why scala is not my ideal language and what I can do with this
Why scala is not my ideal language and what I can do with thisWhy scala is not my ideal language and what I can do with this
Why scala is not my ideal language and what I can do with thisRuslan Shevchenko
 
Deguzmanpresentationprogramming
DeguzmanpresentationprogrammingDeguzmanpresentationprogramming
Deguzmanpresentationprogrammingdeguzmantrisha
 
Kirill Rozin - Practical Wars for Automatization
Kirill Rozin - Practical Wars for AutomatizationKirill Rozin - Practical Wars for Automatization
Kirill Rozin - Practical Wars for AutomatizationSergey Arkhipov
 
Why everyone is excited about Docker (and you should too...) - Carlo Bonamic...
Why everyone is excited about Docker (and you should too...) -  Carlo Bonamic...Why everyone is excited about Docker (and you should too...) -  Carlo Bonamic...
Why everyone is excited about Docker (and you should too...) - Carlo Bonamic...Codemotion
 
"Applied Enterprise Metaprogramming in JavaScript", Vladyslav Dukhin
"Applied Enterprise Metaprogramming in JavaScript", Vladyslav Dukhin"Applied Enterprise Metaprogramming in JavaScript", Vladyslav Dukhin
"Applied Enterprise Metaprogramming in JavaScript", Vladyslav DukhinFwdays
 
Parallelizing CI using Docker Swarm-Mode
Parallelizing CI using Docker Swarm-ModeParallelizing CI using Docker Swarm-Mode
Parallelizing CI using Docker Swarm-ModeAkihiro Suda
 

Similar to Dead-Simple Async Control Flow with Coroutines (20)

How to Reverse Engineer Web Applications
How to Reverse Engineer Web ApplicationsHow to Reverse Engineer Web Applications
How to Reverse Engineer Web Applications
 
Lunch and learn as3_frameworks
Lunch and learn as3_frameworksLunch and learn as3_frameworks
Lunch and learn as3_frameworks
 
Release with confidence
Release with confidenceRelease with confidence
Release with confidence
 
nullcon 2011 - Reversing MicroSoft patches to reveal vulnerable code
nullcon 2011 - Reversing MicroSoft patches to reveal vulnerable codenullcon 2011 - Reversing MicroSoft patches to reveal vulnerable code
nullcon 2011 - Reversing MicroSoft patches to reveal vulnerable code
 
Concurrency patterns
Concurrency patternsConcurrency patterns
Concurrency patterns
 
Le Tour de xUnit
Le Tour de xUnitLe Tour de xUnit
Le Tour de xUnit
 
RichFaces - Testing on Mobile Devices
RichFaces - Testing on Mobile DevicesRichFaces - Testing on Mobile Devices
RichFaces - Testing on Mobile Devices
 
Jump into Squeak - Integrate Squeak projects with Docker & Github
Jump into Squeak - Integrate Squeak projects with Docker & GithubJump into Squeak - Integrate Squeak projects with Docker & Github
Jump into Squeak - Integrate Squeak projects with Docker & Github
 
From Generator to Fiber the Road to Coroutine in PHP
From Generator to Fiber the Road to Coroutine in PHPFrom Generator to Fiber the Road to Coroutine in PHP
From Generator to Fiber the Road to Coroutine in PHP
 
Team Development & Continuous Integration on the Salesforce Platform
Team Development & Continuous Integration on the Salesforce PlatformTeam Development & Continuous Integration on the Salesforce Platform
Team Development & Continuous Integration on the Salesforce Platform
 
Kubernetes 1001
Kubernetes 1001Kubernetes 1001
Kubernetes 1001
 
Fundamentals of programming finals.ajang
Fundamentals of programming finals.ajangFundamentals of programming finals.ajang
Fundamentals of programming finals.ajang
 
Elixir on Containers
Elixir on ContainersElixir on Containers
Elixir on Containers
 
The Hitchhiker's Guide to Faster Builds. Viktor Kirilov. CoreHard Spring 2019
The Hitchhiker's Guide to Faster Builds. Viktor Kirilov. CoreHard Spring 2019The Hitchhiker's Guide to Faster Builds. Viktor Kirilov. CoreHard Spring 2019
The Hitchhiker's Guide to Faster Builds. Viktor Kirilov. CoreHard Spring 2019
 
Why scala is not my ideal language and what I can do with this
Why scala is not my ideal language and what I can do with thisWhy scala is not my ideal language and what I can do with this
Why scala is not my ideal language and what I can do with this
 
Deguzmanpresentationprogramming
DeguzmanpresentationprogrammingDeguzmanpresentationprogramming
Deguzmanpresentationprogramming
 
Kirill Rozin - Practical Wars for Automatization
Kirill Rozin - Practical Wars for AutomatizationKirill Rozin - Practical Wars for Automatization
Kirill Rozin - Practical Wars for Automatization
 
Why everyone is excited about Docker (and you should too...) - Carlo Bonamic...
Why everyone is excited about Docker (and you should too...) -  Carlo Bonamic...Why everyone is excited about Docker (and you should too...) -  Carlo Bonamic...
Why everyone is excited about Docker (and you should too...) - Carlo Bonamic...
 
"Applied Enterprise Metaprogramming in JavaScript", Vladyslav Dukhin
"Applied Enterprise Metaprogramming in JavaScript", Vladyslav Dukhin"Applied Enterprise Metaprogramming in JavaScript", Vladyslav Dukhin
"Applied Enterprise Metaprogramming in JavaScript", Vladyslav Dukhin
 
Parallelizing CI using Docker Swarm-Mode
Parallelizing CI using Docker Swarm-ModeParallelizing CI using Docker Swarm-Mode
Parallelizing CI using Docker Swarm-Mode
 

Recently uploaded

(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Serviceranjana rawat
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSRajkumarAkumalla
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...ranjana rawat
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 
Analog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog ConverterAnalog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog ConverterAbhinavSharma374939
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 

Recently uploaded (20)

(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
 
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINEDJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 
Analog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog ConverterAnalog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog Converter
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 

Dead-Simple Async Control Flow with Coroutines

  • 1. Dead-Simple Async Control Flow with Coroutines by Travis Kaufman (@traviskaufman) github.com/traviskaufman/co-talk-examples
  • 2. Outline Define the problem Async control flow in NodeJS Present the solution Coroutines (surprise!) Explore the implementation How coroutines work under the hood Coroutine libraries Start using them in your apps today! (time permitting) Advanced usage Sample code showing where coroutines really shine
  • 4. Callbacks are UNINTUITIVE source: http://i.imgur.com/DEg3cPZ.png
  • 5. Callbacks are UNINTUITIVE Simple Program: Get GH Username, print out 10 most recently pushed repos https://github.com/traviskaufman/co-talk-examples/blob/master/01-raw-callbacks.js
  • 6. Callbacks are UNINTUITIVE Simple Program: Get GH Username, print out 10 most recently pushed repos https://github.com/traviskaufman/co-talk-examples/blob/master/01-raw-callbacks.js Code duplication
  • 7. Callbacks are UNINTUITIVE Simple Program: Get GH Username, print out 10 most recently pushed repos https://github.com/traviskaufman/co-talk-examples/blob/master/01-raw-callbacks.js Code duplication “Diagonal Development” / Pyramid of Doom / Callback Hell / etc
  • 8. Callbacks are UNINTUITIVE Simple Program: Get GH Username, print out 10 most recently pushed repos https://github.com/traviskaufman/co-talk-examples/blob/master/01-raw-callbacks.js Code duplication Refactoring callbacks means jumping around code to see logical flow of execution :(( “Diagonal Development” / Pyramid of Doom / Callback Hell / etc
  • 9. https://github.com/traviskaufman/co-talk-examples/blob/master/02-async-lib-callbacks.js Callbacks are UNINTUITIVE The “solution”: use a library (e.g. caolan/async, a.k.a. the jQuery of NodeJS)
  • 10. Callbacks are UNINTUITIVE The “solution”: use a library (e.g. caolan/async, a.k.a. the jQuery of NodeJS) Only have to handle this in one place! :D https://github.com/traviskaufman/co-talk-examples/blob/master/02-async-lib-callbacks.js
  • 11. Callbacks are UNINTUITIVE The “solution”: use a library (e.g. caolan/async, a.k.a. the jQuery of NodeJS) Need to be familiar with “async.waterfall” API Change to accommodate lib usage? Only have to handle this in one place! :D https://github.com/traviskaufman/co-talk-examples/blob/master/02-async-lib-callbacks.js
  • 12. Promises to the Rescue! https://github.com/traviskaufman/co-talk-examples/blob/master/03-raw-promises.js No triangles/pyramids/hells/doom/etc. Error handling separated from general logic
  • 13. Promises to the Rescue! but... https://github.com/traviskaufman/co-talk-examples/blob/master/03-raw-promises.js No triangles/pyramids/hells/doom/etc. Error handling separated from general logic API Weirdness still... Still requires handler functions for promise settling
  • 14. Can We Do Better? Readability of synchronous code I/O Efficiency of Asynchronous Code
  • 16. YES! Introducing Coroutines ● coroutine(gen: GeneratorFunction) => Promise ● generator function yields Promises ● values from resolved promises are assigned ● errors from rejected promises are thrown within generator ○ note: could use try/catch inside generator to call handleError() ● Returns Promise for easy interop with other async code ● Best of both worlds! Readability/Intuitiveness + Efficiency/Non-blocking I/O https://github.com/traviskaufman/co-talk-examples/blob/master/04-co-promises.js
  • 18. Coroutines = “Cooperative Routines” Cooperative threads are responsible for explicitly telling executor when they should be suspended Differs from preemptive threads which rely on executor to suspend/resume them Reference (Java-based): http://www.cafeaulait.org/course/ week11/32.html https://www.cs.mtu.edu/~shene/NSF-3/e-Book/FUNDAMENTALS/thread-yield.jpg
  • 19. Coroutines = “Cooperative Routines” Generators provide cooperation through the yield keyword Explicitly tells IO-Loop (uv, etc.) to suspend execution Promises provide the routines Scheduled and run asynchronously by IO-Loop Generators + Promises = Cooperation + Routines = Coroutines! https://www.cs.mtu.edu/~shene/NSF-3/e-Book/FUNDAMENTALS/thread-yield.jpg yield new Promise(...)
  • 21. Coroutine Libraries: tj/co My personal favorite Supports thunks as well as promises Supports yielding arrays/objects (Promise.race), as well as generators (delegation) https://github.com/tj/co
  • 22. Coroutine Libraries: mozilla/task.js Similar to co Very powerful built-in scheduler Adds cancellation to promises Makes coroutines look a lot like thread-based scheduling http://taskjs.org/
  • 23. “But wait, I need ES2015 for this!” Use babelJS (https://babeljs.io/) to transpile your code! Use the --harmony-generators flag with v0.11+ to enable generators (or just -- harmony) Check out petkaantonov/bluebird for an awesome promise polyfill/superset.
  • 24. Advanced Example: “Retry” with exponential backoff
  • 25. Advanced Example: DB Cursoring
  • 26. Additional Resources MDN reference for generator functions https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function* Awesome Promise tutorial from HTML5Rocks http://www.html5rocks.com/en/tutorials/es6/promises/ “Promises and Generators: Control Flow Utopia” - Great presentation by Forbes Lindesay http://pag.forbeslindesay.co.uk/#/ “No Promises: Asynchronous Javascript with only generators” http://www.2ality.com/2015/03/no-promises.html Axel Rauschmayer takes it one step further and shows how you can use generators to write async code without the need for promises. Super interesting stuff!
  • 27. THANK YOU SO MUCH! :D

Editor's Notes

  1. one of the things we software engineers take most seriously is maintainability and readability. You want your code to represent the logical flow of steps to solve the problem at hand.
  2. Mention how I <3 Async and, like jQuery, it is an amazing library
  3. Mention how I <3 Async and, like jQuery, it is an amazing library
  4. Mention how I <3 Async and, like jQuery, it is an amazing library