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

JavaScript Promises - Thinking Sync in an Async...

Kerrick Long
February 06, 2014

JavaScript Promises - Thinking Sync in an Async World

Presented at the STL Ember.js Meetup on 2014-02-06. Video: http://youtu.be/wc72cyYt8-c

Kerrick Long

February 06, 2014
Tweet

More Decks by Kerrick Long

Other Decks in Programming

Transcript

  1. Kerrick Long Things I make and do Where to find

    me online twitter.com/KerrickLong github.com/Kerrick Lead Front-end Developer! at Second Street KerrickLong.com www. meetup.com/STLEmber
  2. var handleError = function(error) {! logError(error);! logOut();! };! getStudent(name, function(error,

    student) {! if (error) return handleError(error);! getLatestGrade(student, function(error, grade) {! if (error) return handleError(error);! console.log(grade);! logOut();! });! });!
  3. var handleError = function(error) {! logError(error);! logOut();! };! getStudent(name, {!

    error: handleError,! success: function(student) {! getLatestGrade(student, {! error: handleError! success: function(grade) {! console.log(grade);! logOut();! },! })! },! });!
  4. var handleError = function(error) {! logError(error);! logOut();! };! getStudent(name, {!

    error: handleError,! success: function(student) {! getLatestGrade(student, {! error: handleError! success: function(grade) {! console.log(grade);! logOut();! },! })! },! });! Awkward.
  5. getJSON('/comments')! .then(function(comments) {! if (comments) return 'Good'! else throw new

    Error('Bad')! }, function(reason) {! // handle getJSON errors! }) Promise.prototype.then
  6. var promises = [ getJSON('/a'),! 'Hi you!', 42, getJSON('/c') ]!

    ! Promise.all(promises)! .then(allFulfilled, firstRejected) Promise.all
  7. function() {! var name = prompt('Your name?')! if (!name)! throw

    new Error('Rude user!')! else! return name! } new Promise()
  8. new Promise(function(fulfill, reject) {! var name = prompt('Your name?')! if

    (!name)! throw new Error('Rude user!')! else! return name! }) new Promise()
  9. new Promise(function(fulfill, reject) {! var name = prompt('Your name?')! if

    (!name)! reject(new Error('Rude user!'))! else! fulfill(name)! }) new Promise()