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

Common Patterns Using Promises

Neal Lindsay
January 07, 2016

Common Patterns Using Promises

Neal Lindsay

January 07, 2016
Tweet

More Decks by Neal Lindsay

Other Decks in Technology

Transcript

  1. 1. falls through if no handler 2. rejected with any

    error thrown 3. resolved with a value returned 4. except… if a promise returned, “becomes” that promise
  2. cache = {}; getUserWithCache = function(id) { return cache[id] =

    cache[id] || getUser(id); }; getUserWithCache(3).then(displayName); // later getUserWithCache(3).then(displayAge);
  3. getOwner = function(obj) { return getPerson(obj.ownerId); }; readName = function(obj)

    { return obj.name; }; getDog('scruffy') .then(getOwner) .then(readName) .then(alert);
  4. multiplyBy = function(x) { return function(y) { return x *

    y; }; }; timesThree = multiplyBy(3); alert(timesThree(2)); // 6
  5. getOwner = function(obj) { return getPerson(obj.ownerId); }; readName = function(obj)

    { return obj.name; }; getDog('scruffy') .then(getOwner) .then(readName) .then(alert);
  6. readProperty = function(propertyName) { return function(obj) { return obj[propertyName]; };

    }; getDog('scruffy') .then(readProperty('ownerId')) .then(getPerson) .then(readProperty('name')) .then(alert);
  7. var getEmergencyDog = function() { return {name: 'claude'}; }; getDog('scruffy')

    .catch(getDefaultDog) .catch(getEmergencyDog) .then(alert);
  8. var getEmergencyDog = function() { return {name: 'claude'}; }; getDog('scruffy')

    .catch(getDefaultDog) .catch(getEmergencyDog) .then(alert);