Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
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 = getUser(id)
console.log(user.name) # won’t work if getUser() is async
# callback
getUser id, (user) -> console.log(...
Promises/A+
The Promise interface represents a proxy for a
value not necessarily known when the
promise is created. It all...
Promises/A+ states
pending initial state, not fulfilled or rejected
fulfilled successful operation
rejected failed operati...
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) ->...
Execute in sequence
getUser(id) (user) ->
getNewTweets user, (tweets) ->
updateTimeline(tweets)
getUser(id).then (user) ->...
Execute in parallel
tmp = []
$http.get('/app/data/first.json').success (data) ->
tmp.push data
$http.get('/app/data/second...
Execute in parallel
first = $http.get('/app/data/first.json')
second = $http.get('/app/data/second.json')
third = $http.ge...
Promise can be cached
getUser: (id) ->
@users ||= {}
@users[id] ||= Api.getUser(id)
then(successCallback, errorCallback, notifyCallback)
updateUser().then(
(res) -> console.log 'Success'
,
(err) -> console....
catch(errorCallback) == promise.then(null, errorCallback)
finally(callback, notifyCallback)
updateUser()
.then (res) -> co...
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) -> ca...
Compatibility
AngularJS:
angularPromise = $q.when($.ajax('/whatever.json'))
Wraps an object that might be a value or a (3r...
AngularJS $q
$q can be used in two fashions
● Kowal's Q or jQuery's Deferred
● other, similar to ES6 promises
Source: http...
Summary
● promises make code much cleaner and
easier to debug and test
● promises can be:
○ chained (each .than modified r...
Read more
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
https://docs.angularjs.org...
Upcoming SlideShare
Loading in …5
×

JavaScript Promises

933 views

Published on

JavaScript Promises

Published in: Software
  • Be the first to comment

  • Be the first to like this

JavaScript Promises

  1. 1. JavaScript Promises @tomaszbak
  2. 2. user = getUser(id) console.log(user.name) # won’t work if getUser() is async
  3. 3. user = getUser(id) console.log(user.name) # won’t work if getUser() is async # callback getUser id, (user) -> console.log(user.name)
  4. 4. 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)
  5. 5. 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
  6. 6. 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
  7. 7. Source: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
  8. 8. Execute in sequence getUser(id) (user) -> getNewTweets user, (tweets) -> updateTimeline(tweets)
  9. 9. Execute in sequence getUser(id) (user) -> getNewTweets user, (tweets) -> updateTimeline(tweets) getUser(id).then (user) -> getNewTweets(user).then (tweets) -> updateTimeline(tweets)
  10. 10. 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)
  11. 11. 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(', ')
  12. 12. 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(', ')
  13. 13. Promise can be cached getUser: (id) -> @users ||= {} @users[id] ||= Api.getUser(id)
  14. 14. 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
  15. 15. 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
  16. 16. Implementations jQuery.promise() Q (Node.js) $q (Angular) RSVP.js (Ember) promise.rb (Ruby) … many more
  17. 17. Compatibility In general, JavaScript promises API will treat anything with a then method as promise-like
  18. 18. 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'}
  19. 19. 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
  20. 20. 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
  21. 21. 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
  22. 22. 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/

×