Power of Promises- September 2011

1,809 views

Published on

Power of Promises

Published in: Technology, Business
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,809
On SlideShare
0
From Embeds
0
Number of Embeds
5
Actions
Shares
0
Downloads
0
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide
  • \n
  • \n
  • \n
  • In a more general CS sense, a promise is something that represents a value returned from an asynchronous operation\n Rewritten in Dojo 1.5, dojo.Deferred is an implementation of the Promises/A CommonJS proposal\n Instances of a Deferred have a promise property that is the "something" that represents the value, without the full control of a Deferred\n
  • \n
  • Take time to walk through the code in detail\n
  • \n
  • Make sure to introduce the API briefly - JSONP endpoints etc\n
  • Take time to walk through the code in detail\n
  • \n
  • Take time to walk through the code in detail\n
  • Take time to walk through the code in detail\n
  • Take time to walk through the code in detail\n
  • Twitter moves fast, so we'll always hit the server for a search, meaning we'll always be returning a promise\n We'll use the results of the new promise from .then to allow us to create a new promise that will represent an array of tweets\n We'll leverage Dojo's QueryResults functionality, which can take either an array or a promise for an array, and returns an array-like object with iterative methods for forEach, filter, and map, but is also a promise itself\n
  • Take time to walk through the code in detail\n
  • Take time to walk through the code in detail\n
  • \n
  • \n\n\n
  • \n
  • Power of Promises- September 2011

    1. 1. The Power of PromisesDojoConfSeptember 16-17, 2011© SitePen, Inc. All Rights Reserved
    2. 2. Who is this guy? Brian Arnold Support Lead & Software Engineer at SitePen, Inc. Lead Engineer on SitePens Dojo Tutorials effort Lead Engineer on SitePens Training Workshops© SitePen, Inc. All Rights Reserved
    3. 3. Asynchronicity is hard General feedback after having taught Deferreds and promises to several classes: The distinction between a Deferred and promise isnt clear Most people dont realize they can make their own Thinking asynchronously is hard at rst© SitePen, Inc. All Rights Reserved
    4. 4. Whats the distinction? A promise is something that represents a value returned from an asynchronous operation Rewritten in Dojo 1.5, dojo.Deferred is an implementation of the Promises/A CommonJS proposal: http://wiki.commonjs.org/wiki/Promises/A© SitePen, Inc. All Rights Reserved
    5. 5. Deferred / Promise API Deferred API Deferred then cancel resolve reject promise Promise API then cancel© SitePen, Inc. All Rights Reserved
    6. 6. The result of then The return of promise.then(someCallback) is a new promise for the return value of someCallback When creating our own APIs we can leverage this functionality, returning the returned promise from .then // Make a request that returns metadata and an array of users var def = dojo.xhrGet({url: "/users", /*...*/}); // Create a new promise for just the users var users = def.then(function(data){ return data.users; }); // Hand back our users return users;© SitePen, Inc. All Rights Reserved
    7. 7. dojo.when (Deferred.when) Handles either promises or values First two arguments promiseOrValue callback When given a promise, it returns a promise for the return of the callback, like .then does© SitePen, Inc. All Rights Reserved
    8. 8. Use Case: Twitter Store API to implement: getIdentity: A way for the store to determine a tweets ID get: A means to retrieve a full set of details for a tweet query: Search Twitter for the provided term and return an array of results© SitePen, Inc. All Rights Reserved
    9. 9. Twitter Store: getIdentity A very trivial piece of our store, but still useful Given a tweet, return its id_str property dojo.declare("my.TwitterStore", null, { idProperty: "id_str", getIdentity: function(/*Object*/ tweet){ // summary: // Returns a tweets identity // tweet: Object // The tweet to get the identity from return tweet[this.idProperty]; }, // ... get and query ... });© SitePen, Inc. All Rights Reserved
    10. 10. Twitter Store: get Store will cache tweets When get is called: If cached, return tweet If not, well retrieve the tweet, but use our own intermediary Deferred to control what it means to be a successful retrieval© SitePen, Inc. All Rights Reserved
    11. 11. Twitter Store: get get: function(/*String*/ id){ // summary: // Gets the full details for a tweet // See https://dev.twitter.com/docs/api/1/get/statuses/show/ %3Aid for details // id: // The identifier as expected by Twitter // Check our index, and if we have it, return it var tweet = this.tweetIndex[id]; if (tweet) { return tweet; } // ...© SitePen, Inc. All Rights Reserved
    12. 12. Twitter Store: get var def = new dojo.Deferred(); // Our intermediary Deferred // Retrieve our tweet var req = dojo.io.script.get({ url: tweetUrl, callbackParamName: callback, content: { id: id } });© SitePen, Inc. All Rights Reserved
    13. 13. Twitter Store: get // Using .then, well set up a graceful handler for success, // as well as what to do with an error req.then( dojo.hitch(this, function(tweet){ if ("error" in tweet) { def.reject(tweet); } else { var id = this.getIdentity(tweet); this.tweetIndex[id] = tweet; def.resolve(tweet); } }), dojo.hitch(def, reject) ); // Hand back our promise return def.promise; } // end get© SitePen, Inc. All Rights Reserved
    14. 14. Twitter Store: query Always hitting the server Use chained promise from .then Lean on Dojos QueryResults functionality© SitePen, Inc. All Rights Reserved
    15. 15. Twitter Store: query query: function(/*String*/query, /*Object?*/ options) { var count = options.count || this.count, searchUrl = options.searchUrl || this.searchUrl, search; // Execute our search search = dojo.io.script.get({ url: searchUrl, callbackParamName: callback, content: { q: query, rpp: count } }); // Hand back a new promise that is *just* for the results array return dojo.store.util.QueryResults( search.then( dojo.hitch(this, _processTweets) ) ); }© SitePen, Inc. All Rights Reserved
    16. 16. Twitter Store: _processTweets _processTweets: function(/*Object*/ res) { // Twitter search results have a property called // `results`, which is just an array of objects var tweets = res.results; // Iterate over our tweets, cleaning a bit. // We are very intentionally *not* saving to tweets index, // as the details for each tweet in search results are sparse. for (var i = 0, l = tweets.length; i < l; ++i) { this._scrubTweet(tweets[i]); } // Hand back the tweets array return tweets; }© SitePen, Inc. All Rights Reserved
    17. 17. Thats it! Thats really all there is to implementing a custom Dojo Object Store Dojo Object Stores are one of the easiest ways that you can start using promises very powerfully right now in your code Being able to create Deferreds and return the promise property allows us to create powerful APIs that allow for clean separation of concerns© SitePen, Inc. All Rights Reserved
    18. 18. SitePen: We help our clients build great apps. Web App Development, Design, Advice Support & Training Strong advocates and contributors of FOSS Works with some amazing companies and organizations:© SitePen, Inc. All Rights Reserved
    19. 19. Thank you! barnold@sitepen.com @brianarn What did you think? Let me know! http://spkr8.com/t/8320© SitePen, Inc. All Rights Reserved

    ×