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
Laravel や Symfony で手っ取り早く OpenAPI のドキュメントを作成する
azuki
2
110
アジャイルを支えるテストアーキテクチャ設計/Test Architecting for Agile
goyoki
9
3.3k
【Kaigi on Rails 2024】YOUTRUST スポンサーLT
krpk1900
1
330
GitHub Actionsのキャッシュと手を挙げることの大切さとそれに必要なこと
satoshi256kbyte
5
430
macOS でできる リアルタイム動画像処理
biacco42
9
2.4k
WebフロントエンドにおけるGraphQL(あるいはバックエンドのAPI)との向き合い方 / #241106_plk_frontend
izumin5210
4
1.4k
TypeScriptでライブラリとの依存を限定的にする方法
tutinoko
2
660
Why Jakarta EE Matters to Spring - and Vice Versa
ivargrimstad
0
1.1k
ローコードSaaSのUXを向上させるためのTypeScript
taro28
1
610
ECS Service Connectのこれまでのアップデートと今後のRoadmapを見てみる
tkikuc
2
250
Quine, Polyglot, 良いコード
qnighy
4
640
Less waste, more joy, and a lot more green: How Quarkus makes Java better
hollycummins
0
100
Featured
See All Featured
Java REST API Framework Comparison - PWX 2021
mraible
PRO
28
8.2k
XXLCSS - How to scale CSS and keep your sanity
sugarenia
246
1.3M
Responsive Adventures: Dirty Tricks From The Dark Corners of Front-End
smashingmag
250
21k
Building a Modern Day E-commerce SEO Strategy
aleyda
38
6.9k
Code Review Best Practice
trishagee
64
17k
Imperfection Machines: The Place of Print at Facebook
scottboms
265
13k
Put a Button on it: Removing Barriers to Going Fast.
kastner
59
3.5k
Side Projects
sachag
452
42k
Teambox: Starting and Learning
jrom
133
8.8k
Build your cross-platform service in a week with App Engine
jlugia
229
18k
Adopting Sorbet at Scale
ufuk
73
9.1k
Learning to Love Humans: Emotional Interface Design
aarron
273
40k
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