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

Practical Promises

Sponsored · Ship Features Fearlessly Turn features on and off without deploys. Used by thousands of Ruby developers.
Avatar for The Guild The Guild
September 05, 2013

Practical Promises

Matthijs Groen talks at the Guild (http://theguild.nl) about Javascript Promises, a design pattern for dealing with asynchronous Javascript calls. Video available at https://vimeo.com/75008316.

Avatar for The Guild

The Guild

September 05, 2013
Tweet

More Decks by The Guild

Other Decks in Programming

Transcript

  1. d i g i t a l c r a

    f t s m a n s h i p Practical Promises
  2. Matthijs Groen • Working @ Kabisa for 3 years •

    Currently developing using Rails and Backbone.js • I believe in the promise of web-applications • Building web applications since 19?? - Opera 5.11 - IE 5.5 - Dail-up modems
  3. Using callbacks with error handling handleData = (result) -> showMessage(result)

    try fetchData onSuccess: handleData onError: showAlternative catch e showMessage(e.message)
  4. Using callbacks with async flows handleData = (result) -> try

    showMessage(result); throw new Error('Broken') catch e # show animation and ask to reload showAnimation 'animation done', onSuccess: animationDone finally showMessage('ask feedback');
  5. Drawbacks of callbacks • Code reads backwards • Error management

    is hard to do • Hard to chain • Hard to explain • Chained callbacks will cause lot of nested code
  6. Using promises (nested) fetchData('data fetched').then( (data) -> showMessage(data) throw new

    Error('broken') ).then( null, (e) -> showAnimation('animation done').then (result) -> showMessage result ).then -> showMessage('ask feedback')
  7. Promising code • Code reads in chronological order • Errors

    will be handled in a natural way (like exceptions) • Uniform way of handling asynchronous processes • Uniform way of handling between all Promises/A+ libraries • Return value will be a promise that delivers the return value or the exception asynchronously
  8. Creating a promise (using q.js) delay = (milliseconds) -> defer

    = Q.defer() setTimeout( -> defer.resolve() milliseconds ) defer.promise delay(500).then -> # and we're off!
  9. Creating a promise (using when.js) delay = (milliseconds) -> defer

    = `when`.defer() setTimeout( -> defer.resolve() milliseconds ) defer.promise delay(500).then -> # and we're off!
  10. jQuery defers # jQuery has no ‘real’ Promises/A promises #

    when.js allows wrapping to convert it to a # real one jDefer = $.ajax() `when(jDefer)`
  11. Chai-as-promised & Mocha-as- promised describe '#someAsyncMethod', -> it 'resolves if

    something succeeds', -> @someMethod().should.become('returnValue') it 'rejects if something fails', -> @someMethod().should.be .rejected.with(Error, 'message')