practical javascript promises

39
Practical JS promises Asa Kusuma github.com/asakusuma/promise-workshop

Upload: asa-kusuma

Post on 29-Nov-2014

247 views

Category:

Software


2 download

DESCRIPTION

Applying promises to real, production applications.

TRANSCRIPT

Page 1: Practical JavaScript Promises

Practical JS promises

Asa Kusuma

github.com/asakusuma/promise-workshop

Page 2: Practical JavaScript Promises

Async operations are 1st class citizens,

represented as objects

Page 3: Practical JavaScript Promises

var loadContainer = showPage('#photo-view'); var loadController = Controller.load(id, authToken); !Promises.all([ loadContainer, loadController ]).then(Controller.pageDidLoad) .then(null, handleError); !loadController.then(null, handleError);

Page 4: Practical JavaScript Promises

pageDidLoad: function(results) { var loadContainerResult = results[0]; var loadControllerResult = results[1]; }

Page 5: Practical JavaScript Promises

load: function(id, authToken) { return DataStore.get(id, authToken) .then(_.bind(this.display, this)); }

Page 6: Practical JavaScript Promises

Compose functions without introducing coupling to the

functions themselves

Page 7: Practical JavaScript Promises

Promise handlers accept a single parameter

Page 8: Practical JavaScript Promises

Functional Programming

• Input arguments

• Do operations

• Return result

• Avoid state

• Avoid mutation

• Avoid side-effects

Page 9: Practical JavaScript Promises

The A+ Spec• 3 states: pending, fulfilled, rejected (settled*)

• .then(), which takes handler functions as params

• Can call multiple times; attach multiple handlers

• Handler called even if then() called after settled

• Once fulfilled or rejected, cannot change state

Page 10: Practical JavaScript Promises

Settled

Pending

Fulfilled Rejected

onFulfilled() onRejected()

Page 11: Practical JavaScript Promises

.then(onFulfill, onReject)

• onFulfill called when promise is fulfilled

• onReject called when promise is rejected

• Return val becomes promise returned by then()***

• Handler execution deferred to nextTick

Page 12: Practical JavaScript Promises

fulfilledPromise .then(function(){ console.log(‘world!’); }); console.log(‘Hello, ’);

Page 13: Practical JavaScript Promises

Promise lingo

• Handler parameter

• Fulfillment value

• Rejection reason

• Resolved == settled

Page 14: Practical JavaScript Promises

Error handling• Error in onFulfill will reject returned promise

• Throwing rejects next promise in chain

• Non A+ features

• Long stack traces

• Global error listener

Page 15: Practical JavaScript Promises

myPromise.then( handleSuccess, handleError );

Page 16: Practical JavaScript Promises

myPromise.then( handleSuccess, handleError ).then(null, handleError);

Page 17: Practical JavaScript Promises

How are promises created?

Page 18: Practical JavaScript Promises

var myPromise = new Promise(function(f, r) { setTimeout(function() { f(‘Hello world’); }, 500); });

Closure Syntax

Page 19: Practical JavaScript Promises

var d = RSVP.defer(); !

setTimeout(function() { d.resolve(‘Hello world’); }, 500); !

var myPromise = d.promise;

Deferred Syntax

Page 20: Practical JavaScript Promises

var partialLoad = promises.defer(); … view.on(‘renderPartial’, function() { partialLoad.fulfill($el); }); … return partialLoad.promise;

Page 21: Practical JavaScript Promises

view.on(‘renderPartial’, _.partial(partialLoad.fulfill, $el));

Page 22: Practical JavaScript Promises

Deferreds are the read-write parent of

the read-only promise

Page 23: Practical JavaScript Promises

Exercise Creating Promises

Page 24: Practical JavaScript Promises

getMessage: function(callback) !

RSVP.defer() new RSVP.Promise(function(f, r) { … })

Page 25: Practical JavaScript Promises

Async or sync? Promise don’t care

Page 26: Practical JavaScript Promises

createContext() .then(fetchUser) .then(initializeRouters) .then(initializeBindings)

Page 27: Practical JavaScript Promises

Use promises to wrap any potentially non-blocking code

Page 28: Practical JavaScript Promises

Common uses of promises• Data retrieval

• Anything involving an external call

• Loading CSS

• Animation

• Template rendering

Page 29: Practical JavaScript Promises

Promise vs Event vs Stream

• Promises are for operations executed once

• Events and streams are for repeated events

• Promises and streams are both object-based

Page 30: Practical JavaScript Promises

High-order functions• Functions that input and/or output functions

• Examples

• _.partial(func, arg)

• _.bind(func, context)

• Very useful with promises

Page 31: Practical JavaScript Promises

myPromise .then(generateSumPartial(5)) .then(output)

Using a high order function

Page 32: Practical JavaScript Promises

function generateSumPartial(n) { return function(resolutionValue) { return n + resolutionValue; } }

The high order function

Page 33: Practical JavaScript Promises

Exercise Advanced Chaining

Page 34: Practical JavaScript Promises

Promise Libraries• Promise creation

• Promise inspection

• Utility functions

• Error handling

• Native vs. Library

Page 35: Practical JavaScript Promises

Utility Functions• .all()/allSettled()

• .hash()

• .spread()

• .map()

• Static vs member functions

Page 36: Practical JavaScript Promises

$.ajax() .then(onFulfill, onReject) .then(output, errorPage);

Where jQuery will $@#% you

Page 37: Practical JavaScript Promises

Testing

• .then() handler always on nextTick

• Most tests assume synchronous

• sinon.stub(process, ‘nextTick’).yields();

• Use the it() callback done handler

Page 38: Practical JavaScript Promises

it(‘should blah’, function(done) { testThis.then(function(result) { expect(result).to.be.ok(); done(); }).then(null, done); });

Page 39: Practical JavaScript Promises

Questions?

[email protected]

github.com/asakusuma/promise-workshop