JavaScript Promises - Thinking Sync in an Async World

2956e2cd2664630aa968b92bbb645f2f?s=47 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

2956e2cd2664630aa968b92bbb645f2f?s=128

Kerrick Long

February 06, 2014
Tweet

Transcript

  1. 2.

    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. 6.

    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. 7.

    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. 9.

    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. 11.
  6. 18.
  7. 35.

    getJSON('/comments')! .then(function(comments) {! if (comments) return 'Good'! else throw new

    Error('Bad')! }, function(reason) {! // handle getJSON errors! }) Promise.prototype.then
  8. 52.

    var promises = [ getJSON('/a'),! 'Hi you!', 42, getJSON('/c') ]!

    ! Promise.all(promises)! .then(allFulfilled, firstRejected) Promise.all
  9. 56.

    function() {! var name = prompt('Your name?')! if (!name)! throw

    new Error('Rude user!')! else! return name! } new Promise()
  10. 57.

    new Promise(function(fulfill, reject) {! var name = prompt('Your name?')! if

    (!name)! throw new Error('Rude user!')! else! return name! }) new Promise()
  11. 58.

    new Promise(function(fulfill, reject) {! var name = prompt('Your name?')! if

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