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

PDF
Intro to Asynchronous Javascript
Garrett Welson
 
PPTX
JavaScript Promises
L&T Technology Services Limited
 
PDF
Asynchronous JavaScript Programming with Callbacks & Promises
Hùng Nguyễn Huy
 
PDF
Introducing Async/Await
Valeri Karpov
 
PDF
Asynchronous JavaScript Programming
Haim Michael
 
PDF
Asynchronous javascript
Eman Mohamed
 
PDF
JavaScript - Chapter 15 - Debugging Techniques
WebStackAcademy
 
PDF
Angular Observables & RxJS Introduction
Rahat Khanna a.k.a mAppMechanic
 
Intro to Asynchronous Javascript
Garrett Welson
 
JavaScript Promises
L&T Technology Services Limited
 
Asynchronous JavaScript Programming with Callbacks & Promises
Hùng Nguyễn Huy
 
Introducing Async/Await
Valeri Karpov
 
Asynchronous JavaScript Programming
Haim Michael
 
Asynchronous javascript
Eman Mohamed
 
JavaScript - Chapter 15 - Debugging Techniques
WebStackAcademy
 
Angular Observables & RxJS Introduction
Rahat Khanna a.k.a mAppMechanic
 

What's hot (20)

PPTX
JS Event Loop
Saai Vignesh P
 
PPTX
JavaScript
Vidyut Singhania
 
PPT
PHP - Introduction to PHP AJAX
Vibrant Technologies & Computers
 
PPTX
1. Arrow Functions | JavaScript | ES6
pcnmtutorials
 
PPTX
React.js - The Dawn of Virtual DOM
Jimit Shah
 
PPT
Javascript arrays
Hassan Dar
 
PPSX
Exception Handling
Reddhi Basu
 
PPT
JavaScript - An Introduction
Manvendra Singh
 
PDF
3. Java Script
Jalpesh Vasa
 
PDF
JavaScript - Chapter 8 - Objects
WebStackAcademy
 
PPTX
ASP.NET Web API
habib_786
 
PPTX
HOW AND WHY GRAALVM IS QUICKLY BECOMING RELEVANT FOR YOU
Lucas Jellema
 
PPTX
Ajax ppt - 32 slides
Smithss25
 
PPT
Ajax Presentation
alaa.moustafa
 
PDF
Expressjs
Yauheni Nikanovich
 
PPT
Introduction to Javascript
Amit Tyagi
 
PPTX
Basic Concept of Node.js & NPM
Bhargav Anadkat
 
PPTX
Node.js Express
Eyal Vardi
 
PDF
Fundamental JavaScript [UTC, March 2014]
Aaron Gustafson
 
PPTX
Advanced JavaScript
Nascenia IT
 
JS Event Loop
Saai Vignesh P
 
JavaScript
Vidyut Singhania
 
PHP - Introduction to PHP AJAX
Vibrant Technologies & Computers
 
1. Arrow Functions | JavaScript | ES6
pcnmtutorials
 
React.js - The Dawn of Virtual DOM
Jimit Shah
 
Javascript arrays
Hassan Dar
 
Exception Handling
Reddhi Basu
 
JavaScript - An Introduction
Manvendra Singh
 
3. Java Script
Jalpesh Vasa
 
JavaScript - Chapter 8 - Objects
WebStackAcademy
 
ASP.NET Web API
habib_786
 
HOW AND WHY GRAALVM IS QUICKLY BECOMING RELEVANT FOR YOU
Lucas Jellema
 
Ajax ppt - 32 slides
Smithss25
 
Ajax Presentation
alaa.moustafa
 
Introduction to Javascript
Amit Tyagi
 
Basic Concept of Node.js & NPM
Bhargav Anadkat
 
Node.js Express
Eyal Vardi
 
Fundamental JavaScript [UTC, March 2014]
Aaron Gustafson
 
Advanced JavaScript
Nascenia IT
 
Ad

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
 

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
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
PPTX
Smart Infrastructure and Automation through IoT Sensors
Rejig Digital
 
PDF
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
PDF
Software Development Company | KodekX
KodekX
 
PDF
REPORT: Heating appliances market in Poland 2024
SPIUG
 
PDF
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
PDF
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
PDF
This slide provides an overview Technology
mineshkharadi333
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PPTX
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira Júnior
 
PDF
CIFDAQ's Teaching Thursday: Moving Averages Made Simple
CIFDAQ
 
PDF
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
PDF
Enable Enterprise-Ready Security on IBM i Systems.pdf
Precisely
 
PPTX
C Programming Basics concept krnppt.pptx
Karan Prajapat
 
PDF
Shreyas_Phanse_Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
SHREYAS PHANSE
 
PDF
Chapter 2 Digital Image Fundamentals.pdf
Getnet Tigabie Askale -(GM)
 
PPTX
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
PDF
Test Bank, Solutions for Java How to Program, An Objects-Natural Approach, 12...
famaw19526
 
PDF
Revolutionize Operations with Intelligent IoT Monitoring and Control
Rejig Digital
 
PDF
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
Smart Infrastructure and Automation through IoT Sensors
Rejig Digital
 
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
Software Development Company | KodekX
KodekX
 
REPORT: Heating appliances market in Poland 2024
SPIUG
 
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
This slide provides an overview Technology
mineshkharadi333
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira Júnior
 
CIFDAQ's Teaching Thursday: Moving Averages Made Simple
CIFDAQ
 
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
Enable Enterprise-Ready Security on IBM i Systems.pdf
Precisely
 
C Programming Basics concept krnppt.pptx
Karan Prajapat
 
Shreyas_Phanse_Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
SHREYAS PHANSE
 
Chapter 2 Digital Image Fundamentals.pdf
Getnet Tigabie Askale -(GM)
 
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
Test Bank, Solutions for Java How to Program, An Objects-Natural Approach, 12...
famaw19526
 
Revolutionize Operations with Intelligent IoT Monitoring and Control
Rejig Digital
 
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 

JavaScript Promises