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

System Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event SchedulingSystem Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event SchedulingBootNeck1
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfROCENODodongVILLACER
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHC Sai Kiran
 
Earthing details of Electrical Substation
Earthing details of Electrical SubstationEarthing details of Electrical Substation
Earthing details of Electrical Substationstephanwindworld
 
Correctly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleCorrectly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleAlluxio, Inc.
 
welding defects observed during the welding
welding defects observed during the weldingwelding defects observed during the welding
welding defects observed during the weldingMuhammadUzairLiaqat
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxk795866
 
US Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionUS Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionMebane Rash
 
Input Output Management in Operating System
Input Output Management in Operating SystemInput Output Management in Operating System
Input Output Management in Operating SystemRashmi Bhat
 
Industrial Safety Unit-IV workplace health and safety.ppt
Industrial Safety Unit-IV workplace health and safety.pptIndustrial Safety Unit-IV workplace health and safety.ppt
Industrial Safety Unit-IV workplace health and safety.pptNarmatha D
 
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTIONTHE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTIONjhunlian
 
The SRE Report 2024 - Great Findings for the teams
The SRE Report 2024 - Great Findings for the teamsThe SRE Report 2024 - Great Findings for the teams
The SRE Report 2024 - Great Findings for the teamsDILIPKUMARMONDAL6
 
Research Methodology for Engineering pdf
Research Methodology for Engineering pdfResearch Methodology for Engineering pdf
Research Methodology for Engineering pdfCaalaaAbdulkerim
 
home automation using Arduino by Aditya Prasad
home automation using Arduino by Aditya Prasadhome automation using Arduino by Aditya Prasad
home automation using Arduino by Aditya Prasadaditya806802
 
An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...Chandu841456
 
Main Memory Management in Operating System
Main Memory Management in Operating SystemMain Memory Management in Operating System
Main Memory Management in Operating SystemRashmi Bhat
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxKartikeyaDwivedi3
 

Recently uploaded (20)

System Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event SchedulingSystem Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event Scheduling
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdf
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECH
 
Earthing details of Electrical Substation
Earthing details of Electrical SubstationEarthing details of Electrical Substation
Earthing details of Electrical Substation
 
Correctly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleCorrectly Loading Incremental Data at Scale
Correctly Loading Incremental Data at Scale
 
welding defects observed during the welding
welding defects observed during the weldingwelding defects observed during the welding
welding defects observed during the welding
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptx
 
US Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionUS Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of Action
 
Input Output Management in Operating System
Input Output Management in Operating SystemInput Output Management in Operating System
Input Output Management in Operating System
 
Industrial Safety Unit-IV workplace health and safety.ppt
Industrial Safety Unit-IV workplace health and safety.pptIndustrial Safety Unit-IV workplace health and safety.ppt
Industrial Safety Unit-IV workplace health and safety.ppt
 
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTIONTHE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
 
The SRE Report 2024 - Great Findings for the teams
The SRE Report 2024 - Great Findings for the teamsThe SRE Report 2024 - Great Findings for the teams
The SRE Report 2024 - Great Findings for the teams
 
Research Methodology for Engineering pdf
Research Methodology for Engineering pdfResearch Methodology for Engineering pdf
Research Methodology for Engineering pdf
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
home automation using Arduino by Aditya Prasad
home automation using Arduino by Aditya Prasadhome automation using Arduino by Aditya Prasad
home automation using Arduino by Aditya Prasad
 
An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...
 
Main Memory Management in Operating System
Main Memory Management in Operating SystemMain Memory Management in Operating System
Main Memory Management in Operating System
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptx
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 

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