SlideShare a Scribd company logo
Globalcode – Open4education
JavaScript Promises
Derek Stavis
Engenheiro de Software
Globalcode – Open4education
Who?
Derek Stavis
github.com/derekstavis
Software Engineer
Ruby, JavaScript, Python, C
Node, React & Webpack Advocate
Globalcode – Open4education
How have you been doing
asynchronous JavaScript?
Globalcode – Open4education
How have you been doing
continuation passing?
Globalcode – Open4education
Using callback functions
// In the browser
setTimeout(function () {
// Will be called in the future
}, 2000);
// In the server
fs.readFile('file.txt', function () {
// Will be called when file.txt is read
});
Globalcode – Open4education
Node.js callback standard
fs.readFile('file.txt', function (err, data) {
// If an error occurred, err will have a value
// Always check for errors using if clauses
})
Globalcode – Open4education
Node.js callback scenario
Let’s say we have a fetch function
It does plain HTTP GET
Accepts a URL and a callback
Callback receives error and response
fetch ('url', function (err, res) { })
Globalcode – Open4education
Node.js callback scenario
fetch('/users/session', function (sessionError, user) {
if (sessionError) {
alert('Error fetching session')
return
}
fetch('/users/' + user.id + '/posts', function
(userErr, posts) {
if (userErr) {
alert('Error fetching user posts')
return
}
renderUserPosts(posts)
})
})
Globalcode – Open4education
Node.js callback hell
Globalcode – Open4education
How could we flatten that tree?
Globalcode – Open4education
new Promise()
Globalcode – Open4education
Formal definition
"A promise represents the eventual
result of an asynchronous
operation."
Globalcode – Open4education
Formal definition
"A promise represents the eventual
result of an asynchronous
operation."
Globalcode – Open4education
Enter Promises
An object which represents and
manage the lifecycle of a future
result
Globalcode – Open4education
Promise states
Pending
Fulfilled Rejected
Globalcode – Open4education
Promise states
Promises aren't reusable
Globalcode – Open4education
Promise API
// New Promises start in "Pending" state
new Promise(function (resolve, reject) {
// Transition to "Rejected" state
reject(new Error('A meaningful error'))
// Transition to "Fulfilled" state
resolve({ my: 'data' })
})
Globalcode – Open4education
Promise API
var promise = new Promise(...)
promise.then(function (result) {
console.log(result)
})
=> { my: "data" }
Globalcode – Open4education
Promise API
var promise = new Promise(...)
promise.catch(function (error) {
console.log(error.message)
})
=> A meaningful error
Globalcode – Open4education
Promise API
Node.js callbacks can be easily
wrapped in promises
Globalcode – Open4education
Promise API
function fetch (url) {
return new Promise(function (resolve, reject) {
request(url, function (err, data) {
if (err) {
reject(err)
} else {
resolve(data)
}
})
}
Globalcode – Open4education
Promise API
Every .then and .catch return a
new promise, so promises are
chainable
Globalcode – Open4education
Flattening the tree
function fetchPosts (user) {
return fetch('/users/' + user.id + '/posts')
}
function fetchSession () {
return fetch('/users/session')
}
fetchSession()
.catch(handleSessionError)
.then(fetchPosts)
.catch(handlePostsError)
.then(renderUserPosts)
Globalcode – Open4education
Flattening the tree
Chaining allows flattening the
callback hell and make continuation
passing look sequential
Globalcode – Open4education
Flattening the tree
const fetchTuples = () =>
Promise.resolve([
[1, 1],
[2, 2],
[6, 4]
])
Globalcode – Open4education
Chaining (a.k.a. sequence monad)
const makeObject = e => ({ l: e[0], r: e[1] })
const attachPlus = e => merge(e, { plus: e.l + e.r })
const attachMinus = e => merge(e, { minus: e.l - e.r })
const attachTimes = e => merge(e, { times: e.l * e.r })
const attachDivide = e => merge(e, { divide: e.l / e.r })
fetchTuples()
.then(map(makeObject))
.then(map(attachPlus))
.then(map(attachMinus))
.then(map(attachTimes))
.then(map(attachDivide))
.then(console.log.bind(console))
Globalcode – Open4education
Chaining (a.k.a. sequence monad)
{ l: 1, r: 1, plus: 2, minus: 0, times: 1, divide: 1 }
{ l: 2, r: 2, plus: 4, minus: 0, times: 4, divide: 1 }
{ l: 6, r: 4, plus: 10, minus: 2, times: 24, divide: 1.5 }
Globalcode – Open4education
Promise Implementation
Promise is a specification
Globalcode – Open4education
Promise Implementation
There are a handful of Promise
implementations
Globalcode – Open4education
Promise Implementation
Solving different issues, focusing
on different areas
Globalcode – Open4education
Promise Implementation
So I have to be tied to a single
implementation?
Globalcode – Open4education
NOT HERE
Globalcode – Open4education
Promises/A+ Contract
https://promisesaplus.com
Globalcode – Open4education
Promises/A+ Contract
Promises/A+ provides interface and
behaviour specification for
interoperable promises
Globalcode – Open4education
Promises/A+ Contract
So you are free to use the
implementation which better fit
your needs while keeping your code
compatible
Globalcode – Open4education
Promises/A+ Contract
This contract was created because
there was no native Promise
specification in ECMAScript
Globalcode – Open4education
ECMAScript 2015 Promise
Since ECMAScript 2015 the Promise
object was included in the spec
https://tc39.github.io/ecma262/#sec-promise-
constructor
Globalcode – Open4education
ECMAScript 2015 Promise
It allows more fun stuff do be done
Globalcode – Open4education
ECMAScript 2015 Promise
Waiting for multiple Promises
Globalcode – Open4education
Waiting for multiple Promises
var promises = [
new Promise(function (resolve, reject) {
setTimeout(resolve, 1000);
}),
new Promise(function (resolve, reject) {
setTimeout(resolve, 2000);
})
]
Promise.all(promises).then(function () {
console.log('Ran after 2 seconds')
})
Globalcode – Open4education
ECMAScript 2015 Promise
Racing multiple Promises
Globalcode – Open4education
Racing multiple Promises
var promises = [
new Promise(function (resolve, reject) {
setTimeout(resolve, 1000);
}),
new Promise(function (resolve, reject) {
setTimeout(resolve, 2000);
})
]
Promise.race(promises).then(function () {
console.log('Ran after 1 second')
})
Globalcode – Open4education
You should definitely look into
Promises
Globalcode – Open4education
Because there's even more!
Globalcode – Open4education
Bluebird
A complete Promise library
http://bluebirdjs.com
Globalcode – Open4education
Bluebird Promise
Catch rejections like exceptions
Globalcode – Open4education
Fine-grained exceptions
function SessionError(message) {
this.message = message
this.name = "SessionError"
Error.captureStackTrace(this, SessionError)
}
SessionError.prototype =
Object.create(Error.prototype)
SessionError.prototype.constructor = SessionError
Globalcode – Open4education
Fine-grained exceptions
function fetchPosts (user) {
throw new PostsError('could not fetch posts')
}
function fetchSession () {
return new SessionError('could not fetch session')
}
fetchSession()
.then(fetchPosts)
.then(renderPosts)
.catch(SessionError, handleSessionError)
.catch(PostsError, handlePostsError)
Globalcode – Open4education
Bluebird Promise
Spread Promise.all result as
parameters
Globalcode – Open4education
Parameter spread
Promise.all([
download('http://foo.bar/file.tar.gz'),
download('http://foo.bar/file.tar.gz.sig')
]).spread((file, signature) =>
sign(file) == signature
? Promise.resolve(file)
: Promise.reject('invalid signature')
)
Globalcode – Open4education
Bluebird Promise
Use .all & .spread for dynamic
amount of promises
When doing fixed number of
promises use .join
Globalcode – Open4education
Join promises results
Promise.join(
download('http://foo.bar/file.tar.gz'),
download('http://foo.bar/file.tar.gz.sig'),
(file, signature) =>
sign(file) == signature
? Promise.resolve(file)
: Promise.reject('invalid signature')
)
Globalcode – Open4education
Bluebird Promise
Resolve objects with promises
Globalcode – Open4education
Join promises results
Promise.props({
file: download('http://foo.bar/file.tar.gz'),
sig: download('http://foo.bar/file.tar.gz.sig')
}).then(data =>
sign(data.file) == data.sig
? Promise.resolve(file)
: Promise.reject('invalid signature')
)
Globalcode – Open4education
Bluebird Promise
Do some .reduce with promises
Globalcode – Open4education
Reduce promises results
const urls = fetchProjects()
Promise.reduce(urls, (total, url) =>
fetch(url).then(data =>
total + data.stars), 0)
Globalcode – Open4education
HTML Fetch
A Promise approach to HTTP requests
https://fetch.spec.whatwg.org
Globalcode – Open4education
#DeprecateXHR
fetch('/users.json')
.then(function(response) {
return response.json()
}).then(function(json) {
console.log('parsed json', json)
}).catch(function(ex) {
console.log('parsing failed', ex)
})
Globalcode – Open4education
#DeprecateXHR
fetch('/users.json')
.then(function(response) {
return response.json()
fetch('/users.json')
.then(function(response) {
return response.json()
}).then(function(json) {
console.log('parsed json', json)
}).catch(function(ex) {
console.log('parsing failed', ex)
})
Globalcode – Open4education
#DeprecateXHR
fetch is growing so powerful
Globalcode – Open4education
#DeprecateXHR
$ telnet mockbin.org 80
GET /bin/2294df68-ae10-4336-a732-3170597543a9 HTTP/1.1
Accept: */*
Host: mockbin.org
HTTP/1.1 200 OK
Content-Type: text/html
Custom-Header: CustomValue
{"fetch": "is so cool"}
Globalcode – Open4education
#DeprecateXHR
fetch promise resolve as soon as
headers are ready
Globalcode – Open4education
Demo
Fetching stuff from Github
https://github.com/derekstavis/
promises-on-the-browser
Globalcode – Open4education
Thanks for watching
Questions?
github.com/derekstavis
twitter.com/derekstavis
facebook.com/derekstavis

More Related Content

What's hot (20)

PDF
Asynchronous JavaScript Programming
Haim Michael
 
PPTX
React + Redux Introduction
Nikolaus Graf
 
PPTX
React js programming concept
Tariqul islam
 
PPTX
Intro to React
Justin Reock
 
PDF
JavaScript Fetch API
Xcat Liu
 
PPTX
Introduction Node.js
Erik van Appeldoorn
 
PDF
Angular - Chapter 4 - Data and Event Handling
WebStackAcademy
 
PDF
An Introduction to Redux
NexThoughts Technologies
 
PPTX
React Hooks
Erez Cohen
 
PDF
Asynchronous javascript
Eman Mohamed
 
PPTX
Introduction to Node js
Akshay Mathur
 
PDF
ES6 presentation
ritika1
 
PPT
JQuery introduction
NexThoughts Technologies
 
PPTX
what is functional component
manojbkalla
 
PPTX
Java 8 Lambda and Streams
Venkata Naga Ravi
 
PPT
Introduction to Javascript
Amit Tyagi
 
PDF
Basics of React Hooks.pptx.pdf
Knoldus Inc.
 
PPTX
Spring Boot
Jiayun Zhou
 
PPTX
React hooks
Ramy ElBasyouni
 
Asynchronous JavaScript Programming
Haim Michael
 
React + Redux Introduction
Nikolaus Graf
 
React js programming concept
Tariqul islam
 
Intro to React
Justin Reock
 
JavaScript Fetch API
Xcat Liu
 
Introduction Node.js
Erik van Appeldoorn
 
Angular - Chapter 4 - Data and Event Handling
WebStackAcademy
 
An Introduction to Redux
NexThoughts Technologies
 
React Hooks
Erez Cohen
 
Asynchronous javascript
Eman Mohamed
 
Introduction to Node js
Akshay Mathur
 
ES6 presentation
ritika1
 
JQuery introduction
NexThoughts Technologies
 
what is functional component
manojbkalla
 
Java 8 Lambda and Streams
Venkata Naga Ravi
 
Introduction to Javascript
Amit Tyagi
 
Basics of React Hooks.pptx.pdf
Knoldus Inc.
 
Spring Boot
Jiayun Zhou
 
React hooks
Ramy ElBasyouni
 

Viewers also liked (8)

PPTX
Awesomely descriptive JavaScript with monads
Michal Nowak
 
PDF
Practical JavaScript Promises
Asa Kusuma
 
PDF
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
andreaslubbe
 
PDF
Introdução ao MongoDB em 30 slides
Derek Willian Stavis
 
PPTX
ECMAScript 6 and the Node Driver
MongoDB
 
PDF
Utilizing Bluebird Promises
Nicholas van de Walle
 
PDF
Promise and Bluebird
Daniel Ku
 
PDF
Packing it all: JavaScript module bundling from 2000 to now
Derek Willian Stavis
 
Awesomely descriptive JavaScript with monads
Michal Nowak
 
Practical JavaScript Promises
Asa Kusuma
 
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
andreaslubbe
 
Introdução ao MongoDB em 30 slides
Derek Willian Stavis
 
ECMAScript 6 and the Node Driver
MongoDB
 
Utilizing Bluebird Promises
Nicholas van de Walle
 
Promise and Bluebird
Daniel Ku
 
Packing it all: JavaScript module bundling from 2000 to now
Derek Willian Stavis
 
Ad

Similar to JavaScript Promises (20)

PDF
Promise is a Promise
Mateusz Bryła
 
PPT
You promise?
IT Weekend
 
PDF
Promises - Asynchronous Control Flow
Henrique Barcelos
 
PDF
A promise is a Promise
Mateusz Bryła
 
PDF
Javascript Promises/Q Library
async_io
 
PDF
Kamil witecki asynchronous, yet readable, code
Kamil Witecki
 
PDF
Introduction to Node JS2.pdf
Bareen Shaikh
 
PDF
I Promise You
William Bruno Moraes
 
PDF
Avoiding callback hell with promises
TorontoNodeJS
 
PPTX
Java Script Promise
Alok Guha
 
PPTX
Avoiding callback hell in Node js using promises
Ankit Agarwal
 
PPTX
Async discussion 9_29_15
Cheryl Yaeger
 
PPTX
Promises, Promises
Domenic Denicola
 
PPTX
The Promised Land (in Angular)
Domenic Denicola
 
PPTX
Ecma script
MOHIT KUMAR
 
PDF
How to actually use promises - Jakob Mattsson, FishBrain
Codemotion Tel Aviv
 
PDF
Getting Comfortable with JS Promises
Asa Kusuma
 
PDF
Asynchronous JavaScript and Promises
Senthil Kumar
 
PPTX
TDC2016SP - Trilha Node.Js
tdc-globalcode
 
PDF
Async js - Nemetschek Presentaion @ HackBulgaria
HackBulgaria
 
Promise is a Promise
Mateusz Bryła
 
You promise?
IT Weekend
 
Promises - Asynchronous Control Flow
Henrique Barcelos
 
A promise is a Promise
Mateusz Bryła
 
Javascript Promises/Q Library
async_io
 
Kamil witecki asynchronous, yet readable, code
Kamil Witecki
 
Introduction to Node JS2.pdf
Bareen Shaikh
 
I Promise You
William Bruno Moraes
 
Avoiding callback hell with promises
TorontoNodeJS
 
Java Script Promise
Alok Guha
 
Avoiding callback hell in Node js using promises
Ankit Agarwal
 
Async discussion 9_29_15
Cheryl Yaeger
 
Promises, Promises
Domenic Denicola
 
The Promised Land (in Angular)
Domenic Denicola
 
Ecma script
MOHIT KUMAR
 
How to actually use promises - Jakob Mattsson, FishBrain
Codemotion Tel Aviv
 
Getting Comfortable with JS Promises
Asa Kusuma
 
Asynchronous JavaScript and Promises
Senthil Kumar
 
TDC2016SP - Trilha Node.Js
tdc-globalcode
 
Async js - Nemetschek Presentaion @ HackBulgaria
HackBulgaria
 
Ad

More from Derek Willian Stavis (6)

PDF
React performance
Derek Willian Stavis
 
PDF
JavaScript Event Loop
Derek Willian Stavis
 
PDF
Node.js cluster
Derek Willian Stavis
 
PDF
Ramda, a functional JavaScript library
Derek Willian Stavis
 
PDF
Forget Grunt and Gulp! Webpack and NPM rule them all!
Derek Willian Stavis
 
PDF
React for Beginners
Derek Willian Stavis
 
React performance
Derek Willian Stavis
 
JavaScript Event Loop
Derek Willian Stavis
 
Node.js cluster
Derek Willian Stavis
 
Ramda, a functional JavaScript library
Derek Willian Stavis
 
Forget Grunt and Gulp! Webpack and NPM rule them all!
Derek Willian Stavis
 
React for Beginners
Derek Willian Stavis
 

Recently uploaded (20)

PDF
Market Wrap for 18th July 2025 by CIFDAQ
CIFDAQ
 
PDF
State-Dependent Conformal Perception Bounds for Neuro-Symbolic Verification
Ivan Ruchkin
 
PDF
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
PDF
Generative AI vs Predictive AI-The Ultimate Comparison Guide
Lily Clark
 
PDF
Build with AI and GDG Cloud Bydgoszcz- ADK .pdf
jaroslawgajewski1
 
PDF
Integrating IIoT with SCADA in Oil & Gas A Technical Perspective.pdf
Rejig Digital
 
PDF
Economic Impact of Data Centres to the Malaysian Economy
flintglobalapac
 
PDF
Market Insight : ETH Dominance Returns
CIFDAQ
 
PDF
Make GenAI investments go further with the Dell AI Factory
Principled Technologies
 
PPTX
Agile Chennai 18-19 July 2025 Ideathon | AI Powered Microfinance Literacy Gui...
AgileNetwork
 
PPTX
AI Code Generation Risks (Ramkumar Dilli, CIO, Myridius)
Priyanka Aash
 
PDF
GDG Cloud Munich - Intro - Luiz Carneiro - #BuildWithAI - July - Abdel.pdf
Luiz Carneiro
 
PDF
introduction to computer hardware and sofeware
chauhanshraddha2007
 
PPTX
Machine Learning Benefits Across Industries
SynapseIndia
 
PPTX
python advanced data structure dictionary with examples python advanced data ...
sprasanna11
 
PDF
How ETL Control Logic Keeps Your Pipelines Safe and Reliable.pdf
Stryv Solutions Pvt. Ltd.
 
PPTX
Simple and concise overview about Quantum computing..pptx
mughal641
 
PDF
SalesForce Managed Services Benefits (1).pdf
TechForce Services
 
PDF
Per Axbom: The spectacular lies of maps
Nexer Digital
 
PDF
How Current Advanced Cyber Threats Transform Business Operation
Eryk Budi Pratama
 
Market Wrap for 18th July 2025 by CIFDAQ
CIFDAQ
 
State-Dependent Conformal Perception Bounds for Neuro-Symbolic Verification
Ivan Ruchkin
 
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
Generative AI vs Predictive AI-The Ultimate Comparison Guide
Lily Clark
 
Build with AI and GDG Cloud Bydgoszcz- ADK .pdf
jaroslawgajewski1
 
Integrating IIoT with SCADA in Oil & Gas A Technical Perspective.pdf
Rejig Digital
 
Economic Impact of Data Centres to the Malaysian Economy
flintglobalapac
 
Market Insight : ETH Dominance Returns
CIFDAQ
 
Make GenAI investments go further with the Dell AI Factory
Principled Technologies
 
Agile Chennai 18-19 July 2025 Ideathon | AI Powered Microfinance Literacy Gui...
AgileNetwork
 
AI Code Generation Risks (Ramkumar Dilli, CIO, Myridius)
Priyanka Aash
 
GDG Cloud Munich - Intro - Luiz Carneiro - #BuildWithAI - July - Abdel.pdf
Luiz Carneiro
 
introduction to computer hardware and sofeware
chauhanshraddha2007
 
Machine Learning Benefits Across Industries
SynapseIndia
 
python advanced data structure dictionary with examples python advanced data ...
sprasanna11
 
How ETL Control Logic Keeps Your Pipelines Safe and Reliable.pdf
Stryv Solutions Pvt. Ltd.
 
Simple and concise overview about Quantum computing..pptx
mughal641
 
SalesForce Managed Services Benefits (1).pdf
TechForce Services
 
Per Axbom: The spectacular lies of maps
Nexer Digital
 
How Current Advanced Cyber Threats Transform Business Operation
Eryk Budi Pratama
 

JavaScript Promises