SlideShare a Scribd company logo
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

PDF
Супер быстрая автоматизация тестирования на iOS
PDF
Vagrant - the essence of DevOps in a tool
PDF
Ignite talks - 自動化的關鍵
PPT
Javaone2008 Bof 5102 Groovybuilders
PDF
Using the Groovy Ecosystem for Rapid JVM Development
PPT
Testing of javacript
PDF
PuppetConf 2014 Killer R10K Workflow With Notes
KEY
Tdd With Groovy
Супер быстрая автоматизация тестирования на iOS
Vagrant - the essence of DevOps in a tool
Ignite talks - 自動化的關鍵
Javaone2008 Bof 5102 Groovybuilders
Using the Groovy Ecosystem for Rapid JVM Development
Testing of javacript
PuppetConf 2014 Killer R10K Workflow With Notes
Tdd With Groovy

What's hot (19)

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

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

PDF
How to Reverse Engineer Web Applications
PPT
Lunch and learn as3_frameworks
PDF
Release with confidence
PPTX
nullcon 2011 - Reversing MicroSoft patches to reveal vulnerable code
PDF
Concurrency patterns
PPTX
Le Tour de xUnit
ODP
RichFaces - Testing on Mobile Devices
PDF
Jump into Squeak - Integrate Squeak projects with Docker & Github
PDF
From Generator to Fiber the Road to Coroutine in PHP
PDF
Good - aDocker - Reference Materials.pdf
PPTX
Team Development & Continuous Integration on the Salesforce Platform
PDF
Kubernetes 1001
PPT
Fundamentals of programming finals.ajang
PDF
Elixir on Containers
PDF
The Hitchhiker's Guide to Faster Builds. Viktor Kirilov. CoreHard Spring 2019
PDF
Why scala is not my ideal language and what I can do with this
PPTX
Deguzmanpresentationprogramming
PDF
Kirill Rozin - Practical Wars for Automatization
PDF
Why everyone is excited about Docker (and you should too...) - Carlo Bonamic...
PDF
"Applied Enterprise Metaprogramming in JavaScript", Vladyslav Dukhin
How to Reverse Engineer Web Applications
Lunch and learn as3_frameworks
Release with confidence
nullcon 2011 - Reversing MicroSoft patches to reveal vulnerable code
Concurrency patterns
Le Tour de xUnit
RichFaces - Testing on Mobile Devices
Jump into Squeak - Integrate Squeak projects with Docker & Github
From Generator to Fiber the Road to Coroutine in PHP
Good - aDocker - Reference Materials.pdf
Team Development & Continuous Integration on the Salesforce Platform
Kubernetes 1001
Fundamentals of programming finals.ajang
Elixir on Containers
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
Deguzmanpresentationprogramming
Kirill Rozin - Practical Wars for Automatization
Why everyone is excited about Docker (and you should too...) - Carlo Bonamic...
"Applied Enterprise Metaprogramming in JavaScript", Vladyslav Dukhin
Ad

Recently uploaded (20)

PPTX
bas. eng. economics group 4 presentation 1.pptx
PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PPTX
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
PDF
R24 SURVEYING LAB MANUAL for civil enggi
PPTX
CYBER-CRIMES AND SECURITY A guide to understanding
PPTX
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PPTX
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PDF
Well-logging-methods_new................
PDF
PPT on Performance Review to get promotions
PPTX
Lecture Notes Electrical Wiring System Components
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PDF
Operating System & Kernel Study Guide-1 - converted.pdf
PPTX
Sustainable Sites - Green Building Construction
PDF
composite construction of structures.pdf
PPTX
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
PPTX
Foundation to blockchain - A guide to Blockchain Tech
PDF
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
DOCX
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
bas. eng. economics group 4 presentation 1.pptx
Model Code of Practice - Construction Work - 21102022 .pdf
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
R24 SURVEYING LAB MANUAL for civil enggi
CYBER-CRIMES AND SECURITY A guide to understanding
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
Well-logging-methods_new................
PPT on Performance Review to get promotions
Lecture Notes Electrical Wiring System Components
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
Operating System & Kernel Study Guide-1 - converted.pdf
Sustainable Sites - Green Building Construction
composite construction of structures.pdf
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
Foundation to blockchain - A guide to Blockchain Tech
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx

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
  • 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

  • #5: 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.
  • #10: Mention how I <3 Async and, like jQuery, it is an amazing library
  • #11: Mention how I <3 Async and, like jQuery, it is an amazing library
  • #12: Mention how I <3 Async and, like jQuery, it is an amazing library