SlideShare ist ein Scribd-Unternehmen logo
1 von 136
Downloaden Sie, um offline zu lesen
Promises,
Generators &
Callbacks!
Oh my!
Writing
asynchronous
code is hard
asynchronous
code is difficult to
read
asynchronous
code is difficult to
write
asynchronous
code is difficult to
maintain
Mike Frey
Why is writing
asynchronous
code hard?
Composition
Patterns
Callbacks
Promises
Generators
Now entering
Nerd War
territory
Goals
Callbacks
vs
Promises
vs
Generators
Callbacks
vs
Promises
vs
Generators
x
x
No
Winner
Unbiased
Informative
Callbacks
How do
they work?
Continuation
Passing
Pass a
function
to another
function
Ask for work now
Handle result later
askForWork(function(err, res) {	
// handle result later	
})
Where are
they used?
Everywhere
Node.js core
User-land
Even
Promises
Benefits
Simple.
Easy to use.
Prolific.
Fast.
Problems
Error
Handling
try{} 	
catch(){}
try{} 	
catch(){}
try {	
doWork(function(res) {	
// handle result	
})	
}	
catch (err) {	
// handle error 	
}
!
doWork(function(err, res) {	
// handle error	
// handle result	
})	
!
!
Homework!
read this:
!
joyent.com/developers/
node/design/errors
Z͈A͡ ̼͔̭͖͕̲
L͝ ͙͖̱
G̠͍̤̠͕
O͢ ̬̫
Z͗̒͊̅ͫ̎
̩̲̤͙̟
Ả͒͐̚
̥̞̥͜
L̀͊ͬ͡
̮̲Ğͥ̈ͩ̓͒
͕̘͉
O͍̼̘͇͔̠͐
!̓̾̆ͪ͆̚͞
asynchronous
or
synchronous
never both
Fix your API:
process.nextTick()
setImmediate()
Fix their API:
dezalgo
Callback
Hell
Composition
problem
Now
Later
Now
Later
Later-er
Now
Later
Later-er
Later-er-er
Now
Later
Later-er
Later-er-er
Later-er-er-er
There’s nothing forcing
you to write ten levels of
nested callbacks, but
the pattern does make
it easy for you to do so.
- Raymond Julin (paraphrased)
Now
Later
Later-er
Later-er-er
Later-er-er-er
Now
Later
Later-er
Later-er-er
Later-er-er-er
getA(function() {	
getB(function() {	
getC(function() {	
// do something	
})	
})	
})
function handleA() {	
getB(handleB)	
}	
function handleB() {	
getC(handleC)	
}	
function handleC() {	
// do something	
}	
getA(handleA)
async
module
async.waterfall([	
getA,	
getB,	
getC	
], 	
function(err, result) {	
// do something	
})
Callbacks
!
Simple.
Everywhere.
Be careful.
Promises
How do
they work?
Eventual
Result
.then()
var promise = doSomething()	
promise.then(	
function (result) {	
// success callback	
},	
function (error) {	
// error callback	
})
Now
Later success
Later failure
Where are
they used?
jQuery
AngularJS
Ember
User-land
Chrome 32
Firefox 29
Opera 19
Node.js 0.11.13
Benefits
Composition:
Chaining &
Error handling
.then()
.then()
.then()
Now
Later success
Later-er success
Later-er-er success
Later-er-er-er success
function addOne(num) {	
return new Promise(	
function(resolve, reject) {	
resolve(num+1)	
})	
}	
!
addOne(0)	
.then(addOne)	
.then(addOne)	
.then(addOne)	
.then(console.log)
function addOne(num) {	
return num+1	
}	
!
var p = new Promise(	
function(res, rej) { res(0) })	
.then(addOne)	
.then(addOne)	
.then(addOne)	
.then(console.log)
Rejections
bubble
Errors
bubble
Now
Later success
Later-er success
Later-er-er success
Any failure
getSpeakers('MidwestJS')	
.then(getGithubUsers)	
.then(getPublicRepos)	
.then(listRepos,	
handleError)
Problems
Slow
Slow
Incompatible
Proposals &
Implementations
jQuery
vs
everyone else
Promises
!
Composable.
Eventual Result.
Generators
What are
they?
How do
they work?
function*
function* tick() {	
!
!
}	
!
!
!
!
function* tick() {	
!
!
}	
!
var itr = tick()	
!
!
function* tick() {	
!
!
}	
!
var itr = tick()	
itr.next()	
!
function* tick() {	
yield 42	
!
}	
!
var itr = tick()	
itr.next().value // 42	
!
yield
function* tick() {	
yield 42	
yield 43	
}	
!
var itr = tick()	
itr.next().value // 42	
itr.next().value // 43	
itr.next().done // true
function* tick() {	
var x = yield	
var y = yield	
}	
!
var itr = tick()	
itr.next()	
itr.next(42) // x becomes 42	
itr.next(43) // y becomes 43
function* tick() {	
var num = 0	
while (!(yield num++));	
}	
!
var itr = tick()	
itr.next().value // 0	
itr.next().value // 1	
itr.next().value // 2
function* tick() {	
var num = 0	
while (!(yield num++));	
}	
!
var itr = tick()	
itr.next().value // 0	
itr.next().value // 1	
itr.next(true).done // true
Replacing
callbacks
function delay(time, callback) {	
setTimeout(function() {	
callback('Slept for ' + time)	
}, time)	
}
function delayThings() {	
delay(1000, function(result1) {	
console.log(result1)	
delay(1200, function(result2) {	
console.log(result2)	
})	
})	
}	
// Slept for 1000	
// Slept for 1200
function* delayThings() {	
var results1 = yield delay(1000)	
console.log(results1)	
!
var results2 = yield delay(1200)	
console.log(results2)	
}
function run(generator) {	
function resume(value) {	
itr.next(value)	
}	
var itr = generator(resume)	
itr.next()	
}
function* delayThings() {	
var results1 = yield delay(1000)	
console.log(results1)	
!
var results2 = yield delay(1200)	
console.log(results2)	
}	
!
function* delayThings(resume) {	
var results1 = yield delay(1000, resume)	
console.log(results1)	
!
var results2 = yield delay(1200, resume)	
console.log(results2)	
}	
!
run(delayThings)
More
callbacks?
thunkify
// simplified from	
// https://github.com/visionmedia/node-thunkify	
!
function thunkify(fn){	
return function(){	
var args = Array.prototype.slice.call(arguments)	
return function(done){	
args.push(function(){	
done.apply(null, arguments)	
})	
fn.apply(null, args)	
}	
}	
}
delay = thunkify(delay)	
!
var thunk = delay(1000)	
!
thunk(function(result) {	
console.log(result)	
})
function run(generator) {	
function resume(value) {	
itr.next(value)	
}	
var itr = generator(resume)	
itr.next()	
}	
!
function run(generator) {	
function resume(ret) {	
var obj = itr.next(ret)	
if (obj.done) return	
obj.value(resume)	
}	
var itr = generator()	
resume()	
}
function* delayThings() {	
var results1 = yield delay(1000)	
console.log(results1)	
!
var results2 = yield delay(1200)	
console.log(results2)	
}	
!
run(delayThings)
yield Now
Later
yield Now
yield Later
Later-er
yield Now
yield Later
yield Later-er
Later-er-er
yield Now
yield Later
yield Later-er
yield Later-er-er
Later-er-er-er
…
co
var delayThings = co(function*() {	
var results1 = yield delay(1000)	
console.log(results1)	
!
var results2 = yield delay(1200)	
console.log(results2)	
})	
!
delayThings()
var delayThings = co(function*() {	
var delays = [delay(1000), delay(1200)]	
var results = yield delays	
!
console.log(results[0])	
console.log(results[1])	
})	
!
delayThings()
Where are
they used?
co
koa
User-land
Firefox 31
Chrome (flag)
Node.js v0.11.10 (flag)
Opera (flag)
Benefits
Feels
synchronous
try{}
catch(){}
New cool
Problems
Support
regenerator
facebook.github.io/regenerator/
traceur
github.com/google/traceur-compiler
Immature
implementations
Generators
!
yield statement.
Pausable function*.
Built for iterators.
Writing
asynchronous
code is hard
But it
doesn’t
have to be!
Call to
action
Explore
Streams
http://nodestreams.com
http://highlandjs.org
Thank you!
Questions?
!
References available here:
github.com/mikefrey/cpg-talk

Weitere ähnliche Inhalte

Was ist angesagt?

Is your C# optimized
Is your C# optimizedIs your C# optimized
Is your C# optimized
Woody Pewitt
 
Lec 38.39 - pointers
Lec 38.39 -  pointersLec 38.39 -  pointers
Lec 38.39 - pointers
Princess Sam
 

Was ist angesagt? (20)

Welcome to Modern C++
Welcome to Modern C++Welcome to Modern C++
Welcome to Modern C++
 
Ruby Code Optimizations (for beginners)
Ruby Code Optimizations (for beginners)Ruby Code Optimizations (for beginners)
Ruby Code Optimizations (for beginners)
 
Node.js System: The Landing
Node.js System: The LandingNode.js System: The Landing
Node.js System: The Landing
 
Pro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScriptPro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScript
 
Operator Overloading
Operator Overloading  Operator Overloading
Operator Overloading
 
Unit Testing Front End JavaScript
Unit Testing Front End JavaScriptUnit Testing Front End JavaScript
Unit Testing Front End JavaScript
 
Ownership System in Rust
Ownership System in RustOwnership System in Rust
Ownership System in Rust
 
Arduino coding class
Arduino coding classArduino coding class
Arduino coding class
 
夜子まま塾講義3(androidで電卓アプリを作る)
夜子まま塾講義3(androidで電卓アプリを作る)夜子まま塾講義3(androidで電卓アプリを作る)
夜子まま塾講義3(androidで電卓アプリを作る)
 
Arduino coding class part ii
Arduino coding class part iiArduino coding class part ii
Arduino coding class part ii
 
Using Akka Futures
Using Akka FuturesUsing Akka Futures
Using Akka Futures
 
Swift - One step forward from Obj-C
Swift -  One step forward from Obj-CSwift -  One step forward from Obj-C
Swift - One step forward from Obj-C
 
Is your C# optimized
Is your C# optimizedIs your C# optimized
Is your C# optimized
 
Rustlabs Quick Start
Rustlabs Quick StartRustlabs Quick Start
Rustlabs Quick Start
 
Lec 38.39 - pointers
Lec 38.39 -  pointersLec 38.39 -  pointers
Lec 38.39 - pointers
 
Effective Modern C++ - Item 35 & 36
Effective Modern C++ - Item 35 & 36Effective Modern C++ - Item 35 & 36
Effective Modern C++ - Item 35 & 36
 
Lec 37 - pointers
Lec 37 -  pointersLec 37 -  pointers
Lec 37 - pointers
 
2621008 - C++ 3
2621008 -  C++ 32621008 -  C++ 3
2621008 - C++ 3
 
Advanced JavaScript
Advanced JavaScript Advanced JavaScript
Advanced JavaScript
 
Multi qubit entanglement
Multi qubit entanglementMulti qubit entanglement
Multi qubit entanglement
 

Ähnlich wie Promises generatorscallbacks

The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)
jeffz
 
Part 3-functions1-120315220356-phpapp01
Part 3-functions1-120315220356-phpapp01Part 3-functions1-120315220356-phpapp01
Part 3-functions1-120315220356-phpapp01
Abdul Samee
 

Ähnlich wie Promises generatorscallbacks (20)

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
 
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
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
 
2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2
 
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)
 
Async History - javascript
Async History - javascriptAsync History - javascript
Async History - javascript
 
3 things you must know to think reactive - Geecon Kraków 2015
3 things you must know to think reactive - Geecon Kraków 20153 things you must know to think reactive - Geecon Kraków 2015
3 things you must know to think reactive - Geecon Kraków 2015
 
Better react/redux apps using redux-saga
Better react/redux apps using redux-sagaBetter react/redux apps using redux-saga
Better react/redux apps using redux-saga
 
C#, What Is Next?
C#, What Is Next?C#, What Is Next?
C#, What Is Next?
 
用 Go 語言打造多台機器 Scale 架構
用 Go 語言打造多台機器 Scale 架構用 Go 語言打造多台機器 Scale 架構
用 Go 語言打造多台機器 Scale 架構
 
Andrii Orlov "Generators Flexibility in Modern Code"
Andrii Orlov "Generators Flexibility in Modern Code"Andrii Orlov "Generators Flexibility in Modern Code"
Andrii Orlov "Generators Flexibility in Modern Code"
 
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
 
The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)
 
Job Queue in Golang
Job Queue in GolangJob Queue in Golang
Job Queue in Golang
 
Workshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptWorkshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScript
 
Go Says WAT?
Go Says WAT?Go Says WAT?
Go Says WAT?
 
Dart function - Recursive functions
Dart function - Recursive functionsDart function - Recursive functions
Dart function - Recursive functions
 
Introduction to go
Introduction to goIntroduction to go
Introduction to go
 
Part 3-functions1-120315220356-phpapp01
Part 3-functions1-120315220356-phpapp01Part 3-functions1-120315220356-phpapp01
Part 3-functions1-120315220356-phpapp01
 

Kürzlich hochgeladen

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Kürzlich hochgeladen (20)

The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 

Promises generatorscallbacks