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
『ドメイン駆動設計をはじめよう』のモデリングアプローチ
masuda220
PRO
8
510
リリース8年目のサービスの1800個のERBファイルをViewComponentに移行した方法とその結果
katty0324
5
4.2k
「今のプロジェクトいろいろ大変なんですよ、app/services とかもあって……」/After Kaigi on Rails 2024 LT Night
junk0612
4
2k
Amazon Bedrock Agentsを用いてアプリ開発してみた!
har1101
0
300
タクシーアプリ『GO』のリアルタイムデータ分析基盤における機械学習サービスの活用
mot_techtalk
4
420
C++でシェーダを書く
fadis
6
3.9k
イベント駆動で成長して委員会
happymana
1
270
とにかくAWS GameDay!AWSは世界の共通言語! / Anyway, AWS GameDay! AWS is the world's lingua franca!
seike460
PRO
1
780
シェーダーで魅せるMapLibreの動的ラスタータイル
satoshi7190
1
440
JaSST 24 九州:ワークショップ(は除く)実践!マインドマップを活用したソフトウェアテスト+活用事例
satohiroyuki
0
450
Sidekiqで実現する 長時間非同期処理の中断と再開 / Pausing and Resuming Long-Running Asynchronous Jobs with Sidekiq
hypermkt
6
3k
Generative AI Use Cases JP (略称:GenU)奮闘記
hideg
0
190
Featured
See All Featured
The Art of Delivering Value - GDevCon NA Keynote
reverentgeek
7
560
CoffeeScript is Beautiful & I Never Want to Write Plain JavaScript Again
sstephenson
159
15k
Imperfection Machines: The Place of Print at Facebook
scottboms
264
13k
Designing for humans not robots
tammielis
249
25k
Understanding Cognitive Biases in Performance Measurement
bluesmoon
26
1.4k
個人開発の失敗を避けるイケてる考え方 / tips for indie hackers
panda_program
92
16k
"I'm Feeling Lucky" - Building Great Search Experiences for Today's Users (#IAC19)
danielanewman
226
22k
Bootstrapping a Software Product
garrettdimon
PRO
305
110k
Intergalactic Javascript Robots from Outer Space
tanoku
268
27k
Done Done
chrislema
181
16k
Design and Strategy: How to Deal with People Who Don’t "Get" Design
morganepeng
126
18k
Speed Design
sergeychernyshev
24
600
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