SlideShare une entreprise Scribd logo
1  sur  26
Télécharger pour lire hors ligne
Hao-kang Den <github @hden>
Harnessing asynchronicity - callbacks, promises,
generators, and coroutines
Agenda
● Why asynchronous?
● Callback
● Promise
● Generator [--harmony]
● Coroutines [--harmony]
Why asynchronous?
Callbacks
Original slides introducing node.js by
Ryan Dahl @jsconf 2009
@ry
@ry
@ry
@ry
@ry
@ry
@ry
@ry
@ry
@ry
@ry
@ry
@ry
@ry
Pyramid of Doom
step1(function (value1) {
step2(value1, function(value2) {
step3(value2, function(value3) {
step4(value3, function(value4) {
// Do something with value4
});
});
});
});
Hairball
Promise/A+
Q.fcall(promisedStep1)
.then(promisedStep2)
.then(promisedStep3)
.then(promisedStep4)
.then(function (value4) {
// Do something with value4
})
.catch(function (error) {
// Handle any error from all above steps
})
.done(); https://github.com/kriskowal/q
ECMAScript a.k.a. JavaScript
● version 1 - June 1997
● version 2 - June 1998
● version 3 - December 1999
● version 4 - Abandoned
● version 5 - December 2009
● version 5.1 - June 2011
● version 6 - [Harmony] Work in progress
Generators
function* fibonacci() {
let [prev, curr] = [0, 1];
for (;;) {
[prev, curr] = [curr, prev + curr];
yield curr;
}
}
let seq = fibonacci();
print(seq.next()); // 1
print(seq.next()); // 2
print(seq.next()); // 3
print(seq.next()); // 5
print(seq.next()); // 8
ECMAScript 6 a.k.a Harmony
Coroutines
var fs = require(‘fs’);
function read(path) {
return function(done){
fs.readFile(path, ‘utf8', done);
}
}
makeCoroutine(function *(){
var a = yield read(‘Readme.md’);
var b = yield read(‘package.json’);
console.log(a);
console.log(b);
});
generator
Koa.js
Expressive middleware for
node.js using generators
-- by the core team of expres
app.use(function *(next){
var start = new Date;
yield next;
var ms = new Date - start;
this.set('X-Response-Time', ms + 'ms');
});
generator
Further Reading
● http://latentflip.com/imperative-vs-declarative/
● https://medium.com/code-adventures/174f1fe66127
● https://github.com/kriskowal/q
● http://taoofcode.net/promise-anti-patterns/
● http://adit.io/posts/2013-04-17-functors,_applicatives,_and_monads_in_pictures.html
read!

Contenu connexe

Tendances

Clojure from ground up
Clojure from ground upClojure from ground up
Clojure from ground upDi Xu
 
Cloud TiDB deep dive
Cloud TiDB deep diveCloud TiDB deep dive
Cloud TiDB deep dive臣 成
 
Closure Compiler vs YUICompressor
Closure Compiler vs YUICompressorClosure Compiler vs YUICompressor
Closure Compiler vs YUICompressorlifesinger
 
ECMAScript 2017
ECMAScript 2017ECMAScript 2017
ECMAScript 2017max peng
 
Java. Есть ли свет в конце тоннеля
Java. Есть ли свет в конце тоннеляJava. Есть ли свет в конце тоннеля
Java. Есть ли свет в конце тоннеляAlexey Demin
 

Tendances (9)

Clojure from ground up
Clojure from ground upClojure from ground up
Clojure from ground up
 
Bas Vodde - The story of LEsS
Bas Vodde - The story of LEsSBas Vodde - The story of LEsS
Bas Vodde - The story of LEsS
 
Cloud TiDB deep dive
Cloud TiDB deep diveCloud TiDB deep dive
Cloud TiDB deep dive
 
Closure Compiler vs YUICompressor
Closure Compiler vs YUICompressorClosure Compiler vs YUICompressor
Closure Compiler vs YUICompressor
 
ECMAScript 2017
ECMAScript 2017ECMAScript 2017
ECMAScript 2017
 
Advanced guide to Quartz plugin
Advanced guide to Quartz pluginAdvanced guide to Quartz plugin
Advanced guide to Quartz plugin
 
Java. Есть ли свет в конце тоннеля
Java. Есть ли свет в конце тоннеляJava. Есть ли свет в конце тоннеля
Java. Есть ли свет в конце тоннеля
 
Null, the Abyss
Null, the AbyssNull, the Abyss
Null, the Abyss
 
Insertion sort
Insertion sortInsertion sort
Insertion sort
 

En vedette

Apptividia product introduction
Apptividia product introductionApptividia product introduction
Apptividia product introductionapptividia
 
Vatiala elementary school in nutshell
Vatiala elementary school in nutshellVatiala elementary school in nutshell
Vatiala elementary school in nutshellAntti Luoma
 
How to make a hermes handbag, hermes birkin bag, kelly bags, shoulder bags
How to make a hermes handbag, hermes birkin bag, kelly bags, shoulder bags How to make a hermes handbag, hermes birkin bag, kelly bags, shoulder bags
How to make a hermes handbag, hermes birkin bag, kelly bags, shoulder bags eloger123
 
8 Reasons Hearing Loss is More Dangerous Than You Think
8 Reasons Hearing Loss is More Dangerous Than You Think8 Reasons Hearing Loss is More Dangerous Than You Think
8 Reasons Hearing Loss is More Dangerous Than You ThinkImaginears, Inc.
 
Pengembangan pengelolahan hasil laut di indonesia copy
Pengembangan pengelolahan hasil laut di indonesia   copyPengembangan pengelolahan hasil laut di indonesia   copy
Pengembangan pengelolahan hasil laut di indonesia copyalfin thariq
 
Food Security - Social Justice (3)
Food Security - Social Justice (3)Food Security - Social Justice (3)
Food Security - Social Justice (3)schofieldteacher
 
Alfred happy moments
Alfred happy momentsAlfred happy moments
Alfred happy momentsrollen31
 
Top content marketing trends of 2014
Top content marketing trends of 2014Top content marketing trends of 2014
Top content marketing trends of 2014boostnet
 
Kanchi Periva Forum - Ebook # 10 - Gaya Sraaddha Special Edition
Kanchi Periva Forum - Ebook # 10 - Gaya Sraaddha Special EditionKanchi Periva Forum - Ebook # 10 - Gaya Sraaddha Special Edition
Kanchi Periva Forum - Ebook # 10 - Gaya Sraaddha Special Editionkanchiperiva
 
Pitch for "Only in Whispers"
Pitch for "Only in Whispers"Pitch for "Only in Whispers"
Pitch for "Only in Whispers"salesian2014as
 
Презентация по теме "Беседа с родителями"
Презентация по теме "Беседа с родителями"Презентация по теме "Беседа с родителями"
Презентация по теме "Беседа с родителями"zarina2014
 

En vedette (18)

Apptividia product introduction
Apptividia product introductionApptividia product introduction
Apptividia product introduction
 
Vatiala elementary school in nutshell
Vatiala elementary school in nutshellVatiala elementary school in nutshell
Vatiala elementary school in nutshell
 
How to make a hermes handbag, hermes birkin bag, kelly bags, shoulder bags
How to make a hermes handbag, hermes birkin bag, kelly bags, shoulder bags How to make a hermes handbag, hermes birkin bag, kelly bags, shoulder bags
How to make a hermes handbag, hermes birkin bag, kelly bags, shoulder bags
 
8 Reasons Hearing Loss is More Dangerous Than You Think
8 Reasons Hearing Loss is More Dangerous Than You Think8 Reasons Hearing Loss is More Dangerous Than You Think
8 Reasons Hearing Loss is More Dangerous Than You Think
 
Lanzarote
LanzaroteLanzarote
Lanzarote
 
Luzerner rahmkaese
Luzerner rahmkaeseLuzerner rahmkaese
Luzerner rahmkaese
 
Weaving
WeavingWeaving
Weaving
 
Molecular viewers
Molecular viewers Molecular viewers
Molecular viewers
 
Pengembangan pengelolahan hasil laut di indonesia copy
Pengembangan pengelolahan hasil laut di indonesia   copyPengembangan pengelolahan hasil laut di indonesia   copy
Pengembangan pengelolahan hasil laut di indonesia copy
 
Food Security - Social Justice (3)
Food Security - Social Justice (3)Food Security - Social Justice (3)
Food Security - Social Justice (3)
 
Alfred happy moments
Alfred happy momentsAlfred happy moments
Alfred happy moments
 
Landscape
LandscapeLandscape
Landscape
 
Top content marketing trends of 2014
Top content marketing trends of 2014Top content marketing trends of 2014
Top content marketing trends of 2014
 
Jay z
Jay zJay z
Jay z
 
Kanchi Periva Forum - Ebook # 10 - Gaya Sraaddha Special Edition
Kanchi Periva Forum - Ebook # 10 - Gaya Sraaddha Special EditionKanchi Periva Forum - Ebook # 10 - Gaya Sraaddha Special Edition
Kanchi Periva Forum - Ebook # 10 - Gaya Sraaddha Special Edition
 
Pitch for "Only in Whispers"
Pitch for "Only in Whispers"Pitch for "Only in Whispers"
Pitch for "Only in Whispers"
 
Презентация по теме "Беседа с родителями"
Презентация по теме "Беседа с родителями"Презентация по теме "Беседа с родителями"
Презентация по теме "Беседа с родителями"
 
Kalpataru aspire
Kalpataru aspireKalpataru aspire
Kalpataru aspire
 

Similaire à Harnessing asynchronicity callbacks, promises, generators, and coroutines

Javascript Promises/Q Library
Javascript Promises/Q LibraryJavascript Promises/Q Library
Javascript Promises/Q Libraryasync_io
 
The evolution of java script asynchronous calls
The evolution of java script asynchronous callsThe evolution of java script asynchronous calls
The evolution of java script asynchronous callsHuy Hoàng Phạm
 
Douglas Crockford: Serversideness
Douglas Crockford: ServersidenessDouglas Crockford: Serversideness
Douglas Crockford: ServersidenessWebExpo
 
Promise: async programming hero
Promise: async programming heroPromise: async programming hero
Promise: async programming heroThe Software House
 
Promises look into the async future
Promises look into the async futurePromises look into the async future
Promises look into the async futureslicejs
 
function* - ES6, generators, and all that (JSRomandie meetup, February 2014)
function* - ES6, generators, and all that (JSRomandie meetup, February 2014)function* - ES6, generators, and all that (JSRomandie meetup, February 2014)
function* - ES6, generators, and all that (JSRomandie meetup, February 2014)Igalia
 
Promises generatorscallbacks
Promises generatorscallbacksPromises generatorscallbacks
Promises generatorscallbacksMike Frey
 
Javascript Promises
Javascript PromisesJavascript Promises
Javascript Promisesintive
 
JRuby @ Boulder Ruby
JRuby @ Boulder RubyJRuby @ Boulder Ruby
JRuby @ Boulder RubyNick Sieger
 
Async js - Nemetschek Presentaion @ HackBulgaria
Async js - Nemetschek Presentaion @ HackBulgariaAsync js - Nemetschek Presentaion @ HackBulgaria
Async js - Nemetschek Presentaion @ HackBulgariaHackBulgaria
 
Developing cross platform desktop application with Ruby
Developing cross platform desktop application with RubyDeveloping cross platform desktop application with Ruby
Developing cross platform desktop application with RubyAnis Ahmad
 
Building resilient services in go
Building resilient services in goBuilding resilient services in go
Building resilient services in goJaehue Jang
 
Torquebox OSCON Java 2011
Torquebox OSCON Java 2011Torquebox OSCON Java 2011
Torquebox OSCON Java 2011tobiascrawley
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation JavascriptRamesh Nair
 
Node.js flow control
Node.js flow controlNode.js flow control
Node.js flow controlSimon Su
 

Similaire à Harnessing asynchronicity callbacks, promises, generators, and coroutines (20)

Javascript Promises/Q Library
Javascript Promises/Q LibraryJavascript Promises/Q Library
Javascript Promises/Q Library
 
The evolution of java script asynchronous calls
The evolution of java script asynchronous callsThe evolution of java script asynchronous calls
The evolution of java script asynchronous calls
 
Sane Async Patterns
Sane Async PatternsSane Async Patterns
Sane Async Patterns
 
Douglas Crockford: Serversideness
Douglas Crockford: ServersidenessDouglas Crockford: Serversideness
Douglas Crockford: Serversideness
 
Promise: async programming hero
Promise: async programming heroPromise: async programming hero
Promise: async programming hero
 
Promises look into the async future
Promises look into the async futurePromises look into the async future
Promises look into the async future
 
function* - ES6, generators, and all that (JSRomandie meetup, February 2014)
function* - ES6, generators, and all that (JSRomandie meetup, February 2014)function* - ES6, generators, and all that (JSRomandie meetup, February 2014)
function* - ES6, generators, and all that (JSRomandie meetup, February 2014)
 
Advanced JavaScript
Advanced JavaScript Advanced JavaScript
Advanced JavaScript
 
Promises generatorscallbacks
Promises generatorscallbacksPromises generatorscallbacks
Promises generatorscallbacks
 
Javascript Promises
Javascript PromisesJavascript Promises
Javascript Promises
 
Promise pattern
Promise patternPromise pattern
Promise pattern
 
JRuby @ Boulder Ruby
JRuby @ Boulder RubyJRuby @ Boulder Ruby
JRuby @ Boulder Ruby
 
Async js - Nemetschek Presentaion @ HackBulgaria
Async js - Nemetschek Presentaion @ HackBulgariaAsync js - Nemetschek Presentaion @ HackBulgaria
Async js - Nemetschek Presentaion @ HackBulgaria
 
Developing cross platform desktop application with Ruby
Developing cross platform desktop application with RubyDeveloping cross platform desktop application with Ruby
Developing cross platform desktop application with Ruby
 
Building resilient services in go
Building resilient services in goBuilding resilient services in go
Building resilient services in go
 
Torquebox OSCON Java 2011
Torquebox OSCON Java 2011Torquebox OSCON Java 2011
Torquebox OSCON Java 2011
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
 
Invoke Dynamic
Invoke DynamicInvoke Dynamic
Invoke Dynamic
 
Node.js flow control
Node.js flow controlNode.js flow control
Node.js flow control
 
非同期javascriptの過去と未来
非同期javascriptの過去と未来非同期javascriptの過去と未来
非同期javascriptの過去と未来
 

Dernier

Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 

Dernier (20)

Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 

Harnessing asynchronicity callbacks, promises, generators, and coroutines