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
Jakarta Concurrencyによる並行処理プログラミングの始め方 (JJUG CCC 2024 Fall)
tnagao7
1
290
A Journey of Contribution and Collaboration in Open Source
ivargrimstad
0
890
弊社の「意識チョット低いアーキテクチャ」10選
texmeijin
5
24k
3 Effective Rules for Using Signals in Angular
manfredsteyer
PRO
0
110
Better Code Design in PHP
afilina
PRO
0
120
CSC509 Lecture 11
javiergs
PRO
0
180
3 Effective Rules for Using Signals in Angular
manfredsteyer
PRO
1
100
イベント駆動で成長して委員会
happymana
1
320
リアーキテクチャxDDD 1年間の取り組みと進化
hsawaji
1
220
Creating a Free Video Ad Network on the Edge
mizoguchicoji
0
120
AWS Lambdaから始まった Serverlessの「熱」とキャリアパス / It started with AWS Lambda Serverless “fever” and career path
seike460
PRO
1
260
よくできたテンプレート言語として TypeScript + JSX を利用する試み / Using TypeScript + JSX outside of Web Frontend #TSKaigiKansai
izumin5210
6
1.7k
Featured
See All Featured
Practical Tips for Bootstrapping Information Extraction Pipelines
honnibal
PRO
10
720
Mobile First: as difficult as doing things right
swwweet
222
8.9k
The Art of Programming - Codeland 2020
erikaheidi
52
13k
Ruby is Unlike a Banana
tanoku
97
11k
Designing for Performance
lara
604
68k
4 Signs Your Business is Dying
shpigford
180
21k
Visualization
eitanlees
145
15k
Helping Users Find Their Own Way: Creating Modern Search Experiences
danielanewman
29
2.3k
Fireside Chat
paigeccino
34
3k
Put a Button on it: Removing Barriers to Going Fast.
kastner
59
3.5k
Building Adaptive Systems
keathley
38
2.3k
Designing Experiences People Love
moore
138
23k
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