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
ActiveSupport::Notifications supporting instrumentation of Rails apps with OpenTelemetry
ymtdzzz
1
230
Quine, Polyglot, 良いコード
qnighy
4
640
ヤプリ新卒SREの オンボーディング
masaki12
0
130
C++でシェーダを書く
fadis
6
4.1k
CSC509 Lecture 09
javiergs
PRO
0
140
EventSourcingの理想と現実
wenas
6
2.3k
最新TCAキャッチアップ
0si43
0
140
광고 소재 심사 과정에 AI를 도입하여 광고 서비스 생산성 향상시키기
kakao
PRO
0
170
色々なIaCツールを実際に触って比較してみる
iriikeita
0
330
LLM生成文章の精度評価自動化とプロンプトチューニングの効率化について
layerx
PRO
2
190
聞き手から登壇者へ: RubyKaigi2024 LTでの初挑戦が 教えてくれた、可能性の星
mikik0
1
130
Jakarta EE meets AI
ivargrimstad
0
140
Featured
See All Featured
Practical Orchestrator
shlominoach
186
10k
Typedesign – Prime Four
hannesfritz
40
2.4k
Rebuilding a faster, lazier Slack
samanthasiow
79
8.7k
Unsuck your backbone
ammeep
668
57k
Become a Pro
speakerdeck
PRO
25
5k
[Rails World 2023 - Day 1 Closing Keynote] - The Magic of Rails
eileencodes
33
1.9k
Creating an realtime collaboration tool: Agile Flush - .NET Oxford
marcduiker
25
1.8k
[RailsConf 2023] Rails as a piece of cake
palkan
52
4.9k
The Success of Rails: Ensuring Growth for the Next 100 Years
eileencodes
44
6.8k
Gamification - CAS2011
davidbonilla
80
5k
VelocityConf: Rendering Performance Case Studies
addyosmani
325
24k
Practical Tips for Bootstrapping Information Extraction Pipelines
honnibal
PRO
10
720
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