es promise - meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. ·...

65
ES Promise Walkthrough @san650

Upload: others

Post on 19-Sep-2020

9 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

ES PromiseWalkthrough

@san650

Page 2: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

Promise

A Promise represents a value which may be available now, or in the future, or never.

A Promise is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers to an asynchronous action's eventual success value or failure reason.

Page 3: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

ECMA Script Promise

Page 4: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

http://caniuse.com/#search=promise

Page 5: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

var promise = new Promise(function(resolve, reject) {

// call resolve or reject

});

promise.then(function(value) {

// work with value

}, function(error) {

// on error

});

Basic usage (I)

Page 6: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

function get(url) { return new Promise(function(resolve, reject) { var req = new XMLHttpRequest();

req.open('GET', url); req.onload = function() { if (req.status == 200) { resolve(req.response); } else { reject(Error(req.statusText)); } }; req.onerror = function() { reject(Error("Network Error")); }; req.send(); });}

Basic usage (II)

Page 7: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

function get(url) { return new Promise(function(resolve, reject) { var req = new XMLHttpRequest();

req.open('GET', url); req.onload = function() { if (req.status == 200) { resolve(req.response); } else { reject(Error(req.statusText)); } }; req.onerror = function() { reject(Error("Network Error")); }; req.send(); });}

Basic usage (III)

Page 8: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

https://github.com/san650?tab=repositories&type=source

Page 9: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

https://api.github.com/users/san650/repos

[ { "id": 40941202, "name": "ember-sokoban", ... }, { "id": 40941203, "name": "tajpado", ... }, ...]

Page 10: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

get('https://api.github.com/users/san650/repos')

.then(function(response) {

var repos = JSON.parse(response);

console.log(repos.map(repo => repo.name));

});

Basic usage (IV)

Page 11: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or
Page 12: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

¿Y si hay un error en la petición?

Page 13: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

function get(url) { return new Promise(function(resolve, reject) { var req = new XMLHttpRequest();

req.open('GET', url); req.onload = function() { if (req.status == 200) { resolve(req.response); } else { reject(Error(req.statusText)); } }; req.onerror = function() { reject(Error("Network Error")); }; req.send(); });}

Page 14: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

get('https://api.github.com/users/san650/repos') .then(function(response) { var repos = JSON.parse(response); console.log(repos.map(repo => repo.name)); }, function(error) { console.warn(error); });

Error handling (I)

Page 15: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

get('https://api.github.com/users/san650/repos') .then(function(response) { var repos = JSON.parse(response); console.log(repos.map(repo => repo.name)); }) .catch(function(error) { console.warn(error); });

Error handling (II)

Page 16: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

.catch(function(reason) {})

=

.then(undefined, function(reason) {})

Error handling (III)

Page 17: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

get('https://api.github.com/users/san650/repos')

.then(function(response) {

return JSON.parse(response);

})

.then(function(repos) {

return repos.map(repo => repo.name);

})

.then(function(names) {

console.log(names);

}); Transforming values (I)

Page 18: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

get('https://api.github.com/users/san650/repos') .then(JSON.parse) .then(function(repos) { return repos.map(repo => repo.name); }) .then(console.log);

Transforming values (II)

Page 19: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

get('https://api.github.com/repos/san650/ceibo') .then(JSON.parse) .then(function(repo) { return get(repo.stargazers_url); }) .then(JSON.parse) .then(function(stars) { console.log(stars.length); });

Queuing async actions (I)

Page 20: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

get('https://api.github.com/repos/san650/ceibo') .then(JSON.parse) .then(function(repo) { return get(repo.stargazers_url); }) .then(JSON.parse) .then(function(stars) { console.log(stars.length); });

Queuing async actions (II)

Page 21: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

get('https://api.github.com/users/san650/repos') .then(function(response) { // ... then 1 }) .catch(function(error) { // ... catch 1 }) .then(function(message) { // ... then 2 });

Ejercicio para el lector

Page 22: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

Then 1

get('...')

Catch 1Then 2

Unhandled errorDone

Page 23: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

Promise.all([ get('https://api.github.com/repos/san650/ceibo'), get('https://api.github.com/repos/san650/ombu')]).then(function(responses) { // array of responses});

Promise.all(iterable)

Page 24: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

Promise.race([ get('https://api.github.com/repos/san650/ceibo'), get('https://api.github.com/repos/san650/ombu')]).then(function(response) { // only one response});

Promise.race(iterable)

Page 25: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

Promise.resolve('a dummy value');

Promise.resolve(value)

Page 26: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

Promise.reject(Error('a failed promise'));

Promise.reject(reason)

Page 27: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

ECMAScript Promise

● new Promise(function(resolve, reject))● then, catch● chaining ● Promise.all● Promise.race● Promise.resolve● Promise.reject

Page 28: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

RSVP.Promise

Page 29: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or
Page 30: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or
Page 31: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

function get(url) { return new RSVP.Promise(function(resolve, reject) { var req = new XMLHttpRequest();

req.open('GET', url); req.onload = function() { if (req.status == 200) { resolve(req.response); } else { reject(Error(req.statusText)); } }; req.onerror = function() { reject(Error("Network Error")); }; req.send(); });}

Basic usage (I)

Page 32: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

function get(url) { return new RSVP.Promise(function(resolve, reject) { var req = new XMLHttpRequest();

req.open('GET', url); req.onload = function() { if (req.status == 200) { resolve(req.response); } else { reject(Error(req.statusText)); } }; req.onerror = function() { reject(Error("Network Error")); }; req.send(); });}

Basic usage (II)

Page 33: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

var deferred = RSVP.defer();

// ...deferred.promise // access the promise

// ...deferred.resolve();

Deferred (I)

Page 34: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

var deferred = RSVP.defer();

btn.onclick = function() { deferred.resolve(42);};

deferred.promise.then(function(value) { console.log(`the answer to life the universe and everything is ${value}`);});

Deferred (II)

Page 35: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

get('https://api.github.com/users/san650/repos') .then(function(response) { // process }) .catch(function(error) { // an error }) .finally(function() { // always runs });

finally

Page 36: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

RSVP.hash({ ceibo: get('https://api.github.com/repos/san650/ceibo'), ombu: get('https://api.github.com/repos/san650/ombu')}).then(function(data) { // data.ceibo // data.ombu});

RSVP.hash

Page 37: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

RSVP.hashSettled({ ceibo: get('https://api.github.com/repos/san650/ceibo'), ombu: get('https://api.github.com/repos/san650/ombu')}).then(function(data) { // data.ceibo -> { state: 'fulfilled', value: value } // data.ombu -> { state: 'rejected', reason: reason }});

RSVP.hashSettled

Page 38: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

RSVP.allSettled([ get('https://api.github.com/repos/san650/ceibo'), get('https://api.github.com/repos/san650/ombu')]).then(function(responses) { // responses[0] -> { state: 'fulfilled', value: value } // responses[1] -> { state: 'rejected', reason: reason }});

RSVP.allSettled

Page 39: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

RSVP.on('created', function(event) { // event.detail // event.label // ...});

RSVP.on('fulfilled', function(event) { // ...});

RSVP.on('rejected', function(event) { // ...});

Instrumentation

Page 40: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

new RSVP.Promise(function(resolve, reject) {}, "a label");

RSVP.Promise.resolve('a value', 'a label');

RSVP.on('created', function(event) { // event.label});

Labelling

Page 41: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

RSVP.on('error', function(reason, label) { if (label) { console.error(label); }

console.assert(false, reason);});

Unhandled errors

Page 42: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

RSVP.Promise

● Deferred● finally● RSVP.hash● RSVP.allSettled● RSVP.hashSettled● RSVP.on(...) instrumentation● RSVP.on('error') unhandled errors● labelling

Page 43: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

Bluebird

Page 44: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or
Page 45: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or
Page 46: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

get('https://api.github.com/repos/san650/ceibo') .timeout(100) .catch(Promise.TimeoutError, function() { // could not get response within 100ms }) .catch(function() { // different error });

timeout

Page 47: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

get('https://api.github.com/repos/san650/ceibo') .timeout(100) .catch(Promise.TimeoutError, function() { // could not get response within 100ms }) .catch(function() { // different error });

Catch with "type matching"

Page 48: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

Cancellation

function get(url) { return new Promise(function(resolve, reject, onCancel) { var xhr = new XMLHttpRequest(); ... onCancel(function() { xhr.abort(); }); });}

Page 49: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

Y mil cosas más...

Page 50: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

Problemas, futures y observables

Page 51: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

Problemas...

Page 52: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

var promise = get('https://api.github.com/users/san650/repos');

btn.onclick = function() {

promise.cancel(); // nope :-(

};

Cancellation

Page 53: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

var promise = new Promise(function(resolve, reject) {

// ...

}).then(function() {

// ...

}).then(function() {

// ...

}).then(function() {

// ...

}).then(function() {

// ...

}); Performance

Page 54: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

get('https://api.github.com/users/san650/repos')

.then(function(response) {

return JSON.parse(response);

})

.then(function(repos) {

return repos.map(repo => repo.name);

})

.then(function(names) {

console.log(names);

});

Inconsistencias, no es lo mismo retornar un valor que retornar una promesa

Page 55: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

Problemas

● No se pueden cancelar● No son lazy, la función executor se ejecuta siempre● Performance● Inconsistencias, no es lo mismo retornar un valor que retornar una promesa

Page 56: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

Futures

Page 57: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

Futures (Fluture)

Much like Promises, Futures represent the value arising from the success or failure of an asynchronous operation (I/O).

Though unlike Promises Futures are lazy and monadic by design. They conform to the Fantasy Land algebraic JavaScript specification.

Page 58: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or
Page 59: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or
Page 60: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

https://github.com/Avaq/Fluture/wiki/Comparison-to-Promises

new Promise((res) => setTimeout(200, res, 'Hello')) .then(x => `${x} world!`) .then(x => get('/foo')) .then(console.log, console.error);

// ------

Future((rej, res) => setTimeout(200, res, 'Hello')) .map(x => `${x} world!`) .chain(x => get('/foo')) .fork(console.error, console.log);

Page 61: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

Observable

Page 62: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

Observable (RxJS)

Is a set of libraries to compose asynchronous and event-based programs using observable collections and Array#extras style composition in JavaScript.

Some differences with promises

● 0 or many values● Sync or async● Lazy● Can be cancelled

Page 63: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/observable.md

// Get stock data somehow

const source = getAsyncStockData();

const subscription = source

.filter(quote => quote.price > 30)

.map(quote => quote.price)

.forEach(price => console.log(`Prices higher than $30: ${price}`);

Page 64: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or
Page 65: ES Promise - Meetupfiles.meetup.com/18755240/promises - walkthrough.pdf · 2016. 10. 20. · Promise A Promise represents a value which may be available now, or in the future, or

Thanks!

@san650