Getting Comfortable with JS Promises

38
Getting comfortable with JS promises Asa Kusuma

description

Getting Comfortable with JS Promises

Transcript of Getting Comfortable with JS Promises

Page 1: Getting Comfortable with JS Promises

Getting comfortable with JS promises

Asa Kusuma

Page 2: Getting Comfortable with JS Promises

JavaScript Async Basics

• Callbacks do not necessarily imply async

• JavaScript code cannot run concurrently*

• setTimeout(fn,0)/setImmediate/nextTick

Page 3: Getting Comfortable with JS Promises

Promises are a replacement for:

doSomething(function(err, result){…});

Page 4: Getting Comfortable with JS Promises

Why callbacks are less than ideal

Page 5: Getting Comfortable with JS Promises

Complex flow control is difficult

Page 6: Getting Comfortable with JS Promises

Once an operation has started, you can’t

add more handlers

Page 7: Getting Comfortable with JS Promises

Operations have a single callback and must be directly coupled to all reacting code.

Page 8: Getting Comfortable with JS Promises

What’s a promise?

Page 9: Getting Comfortable with JS Promises

A promise is an object that represents a potentially asynchronous operation

Page 10: Getting Comfortable with JS Promises

A promise is an object with a then()

function

Page 11: Getting Comfortable with JS 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 12: Getting Comfortable with JS Promises

Settled

Pending

Fulfilled Rejected

onFulfilled() onRejected()

Page 13: Getting Comfortable with JS Promises

.then(onFulfill, onReject)• onFulfill called when promise is fulfilled

• onReject called when promise is rejected

• Handler execution deferred to nextTick

• Handlers have one argument

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

Page 14: Getting Comfortable with JS Promises

Promise lingo

• Handler parameter

• Fulfillment value

• Rejection reason

• Resolved == settled

Page 15: Getting Comfortable with JS Promises

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

Page 16: Getting Comfortable with JS Promises

Exercise 0: Hello World

Page 17: Getting Comfortable with JS Promises

myPromise .then(function(num){ return 2 + num; }).then(function(num2){ return 5 + num2; }).then(printNumber);

Page 18: Getting Comfortable with JS Promises

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

Page 19: Getting Comfortable with JS Promises

Exercise 1: Chaining

Page 20: Getting Comfortable with JS Promises

How are promises created?

Page 21: Getting Comfortable with JS Promises

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

Closure Syntax

Page 22: Getting Comfortable with JS Promises

var d = RSVP.defer(); !

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

var myPromise = d.promise;

Deferred Syntax

Page 23: Getting Comfortable with JS Promises

Deferreds are the read-write parent of

the read-only promise

Page 24: Getting Comfortable with JS Promises

Exercise 2: Creating Promises

Page 25: Getting Comfortable with JS Promises

Why promises?

Page 26: Getting Comfortable with JS Promises

Compose functions without introducing coupling to the

functions themselves

Page 27: Getting Comfortable with JS Promises

Async operations are 1st class citizens,

represented as objects

Page 28: Getting Comfortable with JS Promises

Async or sync? Promise don’t care

Page 29: Getting Comfortable with JS Promises

Sane flow control

Page 30: Getting Comfortable with JS Promises

Use promises to wrap any potentially non-blocking code

Page 31: Getting Comfortable with JS Promises

Common uses of promises• Data retrieval

• Anything involving an external call

• Loading CSS

• Animation

• Template rendering

Page 32: Getting Comfortable with JS 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 33: Getting Comfortable with JS Promises

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

• Examples

• _.partial(func, arg)

• _.bind(func, context)

• Very useful with promises

Page 34: Getting Comfortable with JS Promises

Promise Libraries• Promise creation

• Promise inspection

• Utility functions

• Error handling

• Native vs. Library

Page 35: Getting Comfortable with JS Promises

Utility Functions• .all()/allSettled()

• .hash()

• .spread()

• .map()

• Static vs member functions

Page 36: Getting Comfortable with JS 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 37: Getting Comfortable with JS Promises

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

Where jQuery will $@#% you

Page 38: Getting Comfortable with JS Promises

Questions? +

More Exercises

[email protected]