SlideShare una empresa de Scribd logo
1 de 22
Descargar para leer sin conexión
JavaScript Promises
@tomaszbak
user = getUser(id)
console.log(user.name) # won’t work if getUser() is async
user = getUser(id)
console.log(user.name) # won’t work if getUser() is async
# callback
getUser id, (user) -> console.log(user.name)
user = getUser(id)
console.log(user.name) # won’t work if getUser() is async
# callback
getUser id, (user) -> console.log(user.name)
# promise
getUser(id).then (user) -> console.log(user.name)
Promises/A+
The Promise interface represents a proxy for a
value not necessarily known when the
promise is created. It allows you to associate
handlers to an asynchronous action's eventual
success or failure.
Source: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
Promises/A+ states
pending initial state, not fulfilled or rejected
fulfilled successful operation
rejected failed operation
settled the Promise is either fulfilled or
rejected, but not pending
Source: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
Source: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
Execute in sequence
getUser(id) (user) ->
getNewTweets user, (tweets) ->
updateTimeline(tweets)
Execute in sequence
getUser(id) (user) ->
getNewTweets user, (tweets) ->
updateTimeline(tweets)
getUser(id).then (user) ->
getNewTweets(user).then (tweets) ->
updateTimeline(tweets)
Execute in sequence
getUser(id) (user) ->
getNewTweets user, (tweets) ->
updateTimeline(tweets)
getUser(id).then (user) ->
getNewTweets(user).then (tweets) ->
updateTimeline(tweets)
getUser(id)
.then(getNewTweets)
.then(updateTimeline)
Execute in parallel
tmp = []
$http.get('/app/data/first.json').success (data) ->
tmp.push data
$http.get('/app/data/second.json').success (data) ->
tmp.push data
$http.get('/app/data/third.json').success (data) ->
tmp.push data
$scope.combinedNestedResult = tmp.join(', ')
Execute in parallel
first = $http.get('/app/data/first.json')
second = $http.get('/app/data/second.json')
third = $http.get('/app/data/third.json')
$q.all([first, second, third]).then((result) ->
[result[0], result[1], result[2]]
).then (tmpResult) ->
$scope.combinedResult = tmpResult.join(', ')
Promise can be cached
getUser: (id) ->
@users ||= {}
@users[id] ||= Api.getUser(id)
then(successCallback, errorCallback, notifyCallback)
updateUser().then(
(res) -> console.log 'Success'
,
(err) -> console.log "Error: #{err}"
,
() -> console.log 'Finally'
)
Source: https://docs.angularjs.org/api/ng/service/$q
catch(errorCallback) == promise.then(null, errorCallback)
finally(callback, notifyCallback)
updateUser()
.then (res) -> console.log 'Success'
.catch (err) -> console.log "Error: #{err}"
.finally -> console.log 'Finally'
Source: https://docs.angularjs.org/api/ng/service/$q
Implementations
jQuery.promise()
Q (Node.js)
$q (Angular)
RSVP.js (Ember)
promise.rb (Ruby)
… many more
Compatibility
In general, JavaScript promises API will treat anything with
a then method as promise-like
Compatibility
“anything with a then method” - my tests helper:
@promiseStub = (success, failure) ->
then: (callback) -> callback(success,failure)
Example usage:
spyOn(Api, 'getUser').andReturn promiseStub {id: 1, name: 'Tom'}
Compatibility
AngularJS:
angularPromise = $q.when($.ajax('/whatever.json'))
Wraps an object that might be a value or a (3rd party) then-
able promise into a $q promise
Source: https://docs.angularjs.org/api/ng/service/$q
AngularJS $q
$q can be used in two fashions
● Kowal's Q or jQuery's Deferred
● other, similar to ES6 promises
Source: https://docs.angularjs.org/api/ng/service/$q
Summary
● promises make code much cleaner and
easier to debug and test
● promises can be:
○ chained (each .than modified result for next .than)
○ executed in parallel ( $q.all(promisesArray) )
○ stored (i.e. for caching)
○ passed as argument to function/object/directive/...
○ returned from function
Read more
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
https://docs.angularjs.org/api/ng/service/$q
http://www.webdeveasy.com/javascript-promises-and-angularjs-q-service/

Más contenido relacionado

La actualidad más candente

Boom! Promises/A+ Was Born
Boom! Promises/A+ Was BornBoom! Promises/A+ Was Born
Boom! Promises/A+ Was Born
Domenic Denicola
 
JSON Rules Language
JSON Rules LanguageJSON Rules Language
JSON Rules Language
giurca
 

La actualidad más candente (20)

Avoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAvoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promises
 
Callbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascriptCallbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascript
 
Practical JavaScript Promises
Practical JavaScript PromisesPractical JavaScript Promises
Practical JavaScript Promises
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
The Promised Land (in Angular)
The Promised Land (in Angular)The Promised Land (in Angular)
The Promised Land (in Angular)
 
Javascript Promises/Q Library
Javascript Promises/Q LibraryJavascript Promises/Q Library
Javascript Promises/Q Library
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.js
 
Avoiding callback hell with promises
Avoiding callback hell with promisesAvoiding callback hell with promises
Avoiding callback hell with promises
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScript
 
Boom! Promises/A+ Was Born
Boom! Promises/A+ Was BornBoom! Promises/A+ Was Born
Boom! Promises/A+ Was Born
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
 
Callbacks and control flow in Node js
Callbacks and control flow in Node jsCallbacks and control flow in Node js
Callbacks and control flow in Node js
 
Async Frontiers
Async FrontiersAsync Frontiers
Async Frontiers
 
The evolution of asynchronous javascript
The evolution of asynchronous javascriptThe evolution of asynchronous javascript
The evolution of asynchronous javascript
 
ReactJS
ReactJSReactJS
ReactJS
 
Domains!
Domains!Domains!
Domains!
 
High Performance web apps in Om, React and ClojureScript
High Performance web apps in Om, React and ClojureScriptHigh Performance web apps in Om, React and ClojureScript
High Performance web apps in Om, React and ClojureScript
 
Web Crawling with NodeJS
Web Crawling with NodeJSWeb Crawling with NodeJS
Web Crawling with NodeJS
 
Promises, promises, and then observables
Promises, promises, and then observablesPromises, promises, and then observables
Promises, promises, and then observables
 
JSON Rules Language
JSON Rules LanguageJSON Rules Language
JSON Rules Language
 

Similar a JavaScript Promises

Do you want a SDK with that API? (Nordic APIS April 2014)
Do you want a SDK with that API? (Nordic APIS April 2014)Do you want a SDK with that API? (Nordic APIS April 2014)
Do you want a SDK with that API? (Nordic APIS April 2014)
Nordic APIs
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
Tom Croucher
 

Similar a JavaScript Promises (20)

AngularJS, More Than Directives !
AngularJS, More Than Directives !AngularJS, More Than Directives !
AngularJS, More Than Directives !
 
From Node.js to Design Patterns
From Node.js to Design Patterns From Node.js to Design Patterns
From Node.js to Design Patterns
 
자바스크립트 비동기 코드(Javascript asyncronous code)
자바스크립트 비동기 코드(Javascript asyncronous code)자바스크립트 비동기 코드(Javascript asyncronous code)
자바스크립트 비동기 코드(Javascript asyncronous code)
 
You promise?
You promise?You promise?
You promise?
 
An opinionated intro to Node.js - devrupt hospitality hackathon
An opinionated intro to Node.js - devrupt hospitality hackathonAn opinionated intro to Node.js - devrupt hospitality hackathon
An opinionated intro to Node.js - devrupt hospitality hackathon
 
More to RoC weibo
More to RoC weiboMore to RoC weibo
More to RoC weibo
 
AWS re:Invent 2016: Chalice: A Serverless Microframework for Python (DEV308)
AWS re:Invent 2016: Chalice: A Serverless Microframework for Python (DEV308)AWS re:Invent 2016: Chalice: A Serverless Microframework for Python (DEV308)
AWS re:Invent 2016: Chalice: A Serverless Microframework for Python (DEV308)
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous Javascript
 
The Return of JavaScript: 3 Open-Source Projects that are driving JavaScript'...
The Return of JavaScript: 3 Open-Source Projects that are driving JavaScript'...The Return of JavaScript: 3 Open-Source Projects that are driving JavaScript'...
The Return of JavaScript: 3 Open-Source Projects that are driving JavaScript'...
 
Reduxing like a pro
Reduxing like a proReduxing like a pro
Reduxing like a pro
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node js
 
Angular and The Case for RxJS
Angular and The Case for RxJSAngular and The Case for RxJS
Angular and The Case for RxJS
 
Do you want a SDK with that API? (Nordic APIS April 2014)
Do you want a SDK with that API? (Nordic APIS April 2014)Do you want a SDK with that API? (Nordic APIS April 2014)
Do you want a SDK with that API? (Nordic APIS April 2014)
 
Cервер на Go для мобильной стратегии
Cервер на Go для мобильной стратегииCервер на Go для мобильной стратегии
Cервер на Go для мобильной стратегии
 
How to perform debounce in react
How to perform debounce in reactHow to perform debounce in react
How to perform debounce in react
 
async/await in Swift
async/await in Swiftasync/await in Swift
async/await in Swift
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
ngMess: AngularJS Dependency Injection
ngMess: AngularJS Dependency InjectionngMess: AngularJS Dependency Injection
ngMess: AngularJS Dependency Injection
 
Practical Celery
Practical CeleryPractical Celery
Practical Celery
 
Angular promises and http
Angular promises and httpAngular promises and http
Angular promises and http
 

Más de Tomasz Bak

Rails tobak2005
Rails tobak2005Rails tobak2005
Rails tobak2005
Tomasz Bak
 

Más de Tomasz Bak (18)

Design Patterns in React
Design Patterns in ReactDesign Patterns in React
Design Patterns in React
 
Building React CRUD app in minutes?
Building React CRUD app in minutes?Building React CRUD app in minutes?
Building React CRUD app in minutes?
 
How to migrate large project from Angular to React
How to migrate large project from Angular to ReactHow to migrate large project from Angular to React
How to migrate large project from Angular to React
 
JAMstack
JAMstackJAMstack
JAMstack
 
e2e testing with cypress
e2e testing with cypresse2e testing with cypress
e2e testing with cypress
 
How to GraphQL: React Apollo
How to GraphQL: React ApolloHow to GraphQL: React Apollo
How to GraphQL: React Apollo
 
How to GraphQL
How to GraphQLHow to GraphQL
How to GraphQL
 
Working with npm packages
Working with npm packagesWorking with npm packages
Working with npm packages
 
How to replace rails asset pipeline with webpack?
How to replace rails asset pipeline with webpack?How to replace rails asset pipeline with webpack?
How to replace rails asset pipeline with webpack?
 
Functional Reactive Angular 2
Functional Reactive Angular 2 Functional Reactive Angular 2
Functional Reactive Angular 2
 
Jak wnieść wkład w Open Source?
Jak wnieść wkład w Open Source?Jak wnieść wkład w Open Source?
Jak wnieść wkład w Open Source?
 
Replacing Rails asset pipeline with Gulp
Replacing Rails asset pipeline with GulpReplacing Rails asset pipeline with Gulp
Replacing Rails asset pipeline with Gulp
 
Ulepszanie aplikacji webowej z AngularJS
Ulepszanie aplikacji webowej z AngularJSUlepszanie aplikacji webowej z AngularJS
Ulepszanie aplikacji webowej z AngularJS
 
Bardziej produktywny gmail
Bardziej produktywny gmailBardziej produktywny gmail
Bardziej produktywny gmail
 
Kerberos
KerberosKerberos
Kerberos
 
Rails tobak2005
Rails tobak2005Rails tobak2005
Rails tobak2005
 
Ldap novell
Ldap novellLdap novell
Ldap novell
 
Testowanie JavaScript
Testowanie JavaScriptTestowanie JavaScript
Testowanie JavaScript
 

Último

Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
masabamasaba
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
masabamasaba
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
masabamasaba
 

Último (20)

Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaS
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the Situation
 
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 

JavaScript Promises