Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Taking Promises Seriously

Taking Promises Seriously

Promises are now truly part of the JavaScript language. This means we can write against a single full-featured promise API to build lightweight, composable libraries which dramatically reduce the complexity of our code at every level of abstraction.

Video from JSConf UY: https://www.youtube.com/watch?v=CVG6mCQrKoI

Avatar for James MacAulay

James MacAulay

March 14, 2014

Other Decks in Programming

Transcript

  1. FYI

  2. 3 Kinds of Functions in this Talk • native (e.g.

    Promise.resolve) • defined in the talk (e.g. wait) • defined in some library (kozu.when)
  3. get

  4. ✍

  5. 2 reasons to use .then • produce side-effects (e.g. DOM

    manipulation) • return new transformed values
  6. getJSON("/post/1.json").then(function(post) { return getJSON(post.commentURL); }).then(function(comments) { // proceed with access

    to posts and comments }).catch(function(error) { // handle errors in either of the two requests }); from https://github.com/tildeio/rsvp.js
  7. getJSON("/post/1.json").then(function(post) { return getJSON(post.commentURL); }).then(function(comments) { // proceed with access

    to posts and comments }).catch(function(error) { // handle errors in either of the two requests }); from https://github.com/tildeio/rsvp.js
  8. Promises seem lame: • we still rely on handler functions

    • trade callback hell for chaining hell
  9. App = Ember.Application.create({}); ! App.IndexRoute = Ember.Route.extend({ model: function(){ return

    [ {firstName: 'Kris', lastName: 'Selden'}, {firstName: 'Luke', lastName: 'Melia'}, {firstName: 'Formerly Alex', lastName: 'Matchneer'} ]; } }); from the ember-latest jsfiddle: http://jsfiddle.net/NQKvy/
  10. App = Ember.Application.create({}); ! App.IndexRoute = Ember.Route.extend({ model: function(){ return

    Promise.resolve([ {firstName: 'Kris', lastName: 'Selden'}, {firstName: 'Luke', lastName: 'Melia'}, {firstName: 'Formerly Alex', lastName: 'Matchneer'} ]); } });
  11. var things = [ {name: 'foo'}, Promise.resolve({name: 'bar'}) ]; !

    var namesPromise = when.map(things, function(t) { return t.name; }); https://github.com/cujojs/when/blob/master/docs/api.md#whenmap