Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
JavaScript Promises - Thinking Sync in an Async...
Search
Kerrick Long
February 06, 2014
Programming
20
7.6k
JavaScript Promises - Thinking Sync in an Async World
Presented at the STL Ember.js Meetup on 2014-02-06. Video:
http://youtu.be/wc72cyYt8-c
Kerrick Long
February 06, 2014
Tweet
Share
More Decks by Kerrick Long
See All by Kerrick Long
15 Things You Shouldn't Do In Ember Anymore
kerrick
0
1.1k
The ECMAScript formerly known as 6
kerrick
0
1.2k
CSS Study Group 1
kerrick
0
1.2k
CSS Study Group 2
kerrick
1
1k
Services & Component Collaboration
kerrick
0
750
Donate STL #Build4STL Hackathon Keynote
kerrick
0
330
Donate STL
kerrick
0
810
TDD With Ember.js
kerrick
0
1.1k
Other Decks in Programming
See All in Programming
Creating a Free Video Ad Network on the Edge
mizoguchicoji
0
120
Streams APIとTCPフロー制御 / Web Streams API and TCP flow control
tasshi
2
350
Remix on Hono on Cloudflare Workers
yusukebe
1
280
WebフロントエンドにおけるGraphQL(あるいはバックエンドのAPI)との向き合い方 / #241106_plk_frontend
izumin5210
4
1.4k
最新TCAキャッチアップ
0si43
0
140
AI時代におけるSRE、 あるいはエンジニアの生存戦略
pyama86
6
1.1k
Make Impossible States Impossibleを 意識してReactのPropsを設計しよう
ikumatadokoro
0
170
ECS Service Connectのこれまでのアップデートと今後のRoadmapを見てみる
tkikuc
2
250
as(型アサーション)を書く前にできること
marokanatani
9
2.6k
色々なIaCツールを実際に触って比較してみる
iriikeita
0
330
Realtime API 入門
riofujimon
0
150
CSC509 Lecture 12
javiergs
PRO
0
160
Featured
See All Featured
jQuery: Nuts, Bolts and Bling
dougneiner
61
7.5k
The Cult of Friendly URLs
andyhume
78
6k
A better future with KSS
kneath
238
17k
Automating Front-end Workflow
addyosmani
1366
200k
Put a Button on it: Removing Barriers to Going Fast.
kastner
59
3.5k
Building Better People: How to give real-time feedback that sticks.
wjessup
364
19k
Designing on Purpose - Digital PM Summit 2013
jponch
115
7k
The Pragmatic Product Professional
lauravandoore
31
6.3k
個人開発の失敗を避けるイケてる考え方 / tips for indie hackers
panda_program
93
16k
Visualization
eitanlees
145
15k
Code Reviewing Like a Champion
maltzj
520
39k
VelocityConf: Rendering Performance Case Studies
addyosmani
325
24k
Transcript
JavaScript Promises Thinking Sync in an Async World then
Kerrick Long Things I make and do Where to find
me online twitter.com/KerrickLong github.com/Kerrick Lead Front-end Developer! at Second Street KerrickLong.com www. meetup.com/STLEmber
try {! console.log(getLatestGrade(getStudent(name)));! }! catch (error) {! logError(error);! }! finally
{! logOut();! }!
try {! console.log(getLatestGrade(getStudent(name)));! }! catch (error) {! logError(error);! }! finally
{! logOut();! }! XMLHttpRequest
getStudent(name, function(student) {! getLatestGrade(student, function(grade) {! console.log(grade);! logOut();! });! });!
var handleError = function(error) {! logError(error);! logOut();! };! getStudent(name, function(error,
student) {! if (error) return handleError(error);! getLatestGrade(student, function(error, grade) {! if (error) return handleError(error);! console.log(grade);! logOut();! });! });!
var handleError = function(error) {! logError(error);! logOut();! };! getStudent(name, {!
error: handleError,! success: function(student) {! getLatestGrade(student, {! error: handleError! success: function(grade) {! console.log(grade);! logOut();! },! })! },! });!
try {! console.log(getLatestGrade(getStudent(name)));! }! catch (error) {! logError(error);! }! finally
{! logOut();! }! Awesome
var handleError = function(error) {! logError(error);! logOut();! };! getStudent(name, {!
error: handleError,! success: function(student) {! getLatestGrade(student, {! error: handleError! success: function(grade) {! console.log(grade);! logOut();! },! })! },! });! Awkward.
getStudent(name)! .then(getLatestGrade)! .then(console.log)! .catch(logError)! .then(logOut)! ;! Promises
None
Promise Basics
Promise Basics Consuming Promises
Promise Basics Consuming Promises Creating Promises
Promise Basics Consuming Promises Creating Promises Advanced Techniques
Promise Basics
Getting Promises
None
RSVP.js Q.js • Bluebird
RSVP.js Q.js • Bluebird Promises/A+
Promise Guarantees
Always Async
Always Async Returns a Promise
Always Async Returns a Promise Handled Once
Always Async Returns a Promise Handled Once Then’able
Promise States
Promise States Pending Fulfilled Rejected
Promise States Pending Fulfilled Rejected } Settled
Promise States Pending Fulfilled Rejected
Promise States Pending Fulfilled Rejected Value Reason
Promise States Pending Fulfilled Rejected Return Value Thrown Exception
Consuming Promises
Promise Prototype Methods
getJSON('/comments')! .then(onFulfilled, onRejected) Promise.prototype.then
getJSON('/comments')! .then(function(comments) {! if (comments) return 'Good'! else throw new
Error('Bad')! }, function(reason) {! // handle getJSON errors! }) Promise.prototype.then
getJSON('/comments')! .then(fulfillOne, rejectOne)! .then(fulfillTwo)! .then(null, rejectTwo) Promise.prototype.then
getJSON('/comments')! .then(fulfillOne, rejectOne)! .then(fulfillTwo)! .then(null, rejectTwo) Promise.prototype.then THROW
getJSON('/comments')! .then(fulfillOne, rejectOne)! .then(fulfillTwo)! .then(null, rejectTwo) Promise.prototype.then THROW
getJSON onFulfilled onRejected getJSON onFulfilled onRejected
getJSON('/comments') // waiting...! .then(extractFirstId)! .then(getCommentById) // waiting...! .then(showComment) Promise.prototype.then
var promise = getJSON('/comments');! somethingElse();! promise.then(onFulfilled, onRejected); Promise.prototype.then
getJSON('/comments')! .then(null, onRejected) Promise.prototype.catch
getJSON('/comments')! .catch(onRejected) Promise.prototype.catch
Promise Static Methods
Promise.cast('Hi you!')! .then(onFulfilled, onRejected) Promise.cast
Promise.cast(seededRandom(42))! .then(onFulfilled, onRejected) Promise.cast
Promise.cast($.ajax(config))! .then(onFulfilled, onRejected) Promise.cast
$.ajax(config)! .then(onFulfilled, onRejected)
$.ajax(config)! .then(onFulfilled, onRejected) Lies, all LIES!
Promise.cast($.ajax(config))! .then(onFulfilled, onRejected) Promise.cast
var promises = [ getJSON('/a'),! getJSON('/b'), getJSON('/c') ]! ! Promise.all(promises)!
.then(allFulfilled, firstRejected) Promise.all
var promises = [ getJSON('/a'),! 'Hi you!', 42, getJSON('/c') ]!
! Promise.all(promises)! .then(allFulfilled, firstRejected) Promise.all
var promises = [ saveTo(server1),! saveTo(server2), saveTo(server3) ]! ! Promise.race(promises)!
.then(firstFulfilled, firstRejected) Promise.race
Creating Promises
new Promise()
function() {! var name = prompt('Your name?')! if (!name)! throw
new Error('Rude user!')! else! return name! } new Promise()
new Promise(function(fulfill, reject) {! var name = prompt('Your name?')! if
(!name)! throw new Error('Rude user!')! else! return name! }) new Promise()
new Promise(function(fulfill, reject) {! var name = prompt('Your name?')! if
(!name)! reject(new Error('Rude user!'))! else! fulfill(name)! }) new Promise()
Shortcuts
new Promise(function(fulfill, reject) {! fulfill(something)! }) Promise.resolve()
new Promise(function(fulfill, reject) {! fulfill(something)! })! Promise.resolve(something) Promise.resolve()
new Promise(function(fulfill, reject) {! reject(something)! }) Promise.reject()
new Promise(function(fulfill, reject) {! reject(something)! })! Promise.reject(something) Promise.reject()
Advanced Techniques
this.get('name') // 'Kerrick'! ! getJSON('/comments')! .then(function(comments) {! this.get('name') // throws!
}) this and bind()
this.get('name') // 'Kerrick'! var self = this! getJSON('/comments')! .then(function(comments) {!
self.get('name') // 'Kerrick'! }) this and bind()
this.get('name') // 'Kerrick'! ! getJSON('/comments')! .then(function(comments) {! this.get('name') // 'Kerrick'!
}.bind(this)) this and bind()
getJSON('/comments')! .then(function(comments) {! throw new Error('Hello?')! }) Absorbed Rejections
getJSON('/comments')! .then(function(comments) {! throw new Error('Hello?')! })! .catch(console.error.bind(console)) Absorbed Rejections
getStudent(name) // <Promise>! .then(getLatestGrade)! .then(log)! .catch(logError)! .then(logOut) Promise-aware Functions
log(getLatestGrade(getStudent(name)))! .catch(logError)! .then(logOut) Promise-aware Functions
function getLatestGrade(promise) {! return Promise.cast(promise)! .then(function(value) {! // getLatestGrade Logic!
})! } Promise-aware Functions