Slide 1

Slide 1 text

Assincronia em Javascript Breno Ferreira @breno_ferreira github.com/brenoferreira

Slide 2

Slide 2 text

Fora do mundo JS, a maior parte do código que escrevemos é síncrono.

Slide 3

Slide 3 text

var client = new WebClient(); var html = client.DownloadString("http:/ /www.google.com"); Console.WriteLine(html);

Slide 4

Slide 4 text

Em JS, nosso código é assíncrono Afinal, só temos 1 thread, e não podemos nos dar ao luxo de esperar algo terminar.

Slide 5

Slide 5 text

Isso nos força a usar callbacks

Slide 6

Slide 6 text

Quem nunca fez isso? (Piramid of Doom) $.get('http:/ /whateverjson.com', { ! success: function(json1){ ! ! ... ! ! $.post('http:/ /xpto.com', data, { ! ! ! ... ! ! ! success: function(res){ ! ! ! ! $.get('http:/ /anotherjson.com', { ! ! ! ! ! success: function(json2){ ! ! ! ! ! ! .... ! ! ! ! ! } ! ! ! ! }); ! ! ! } ! ! }); ! } });

Slide 7

Slide 7 text

Reações <- Sua!

Slide 8

Slide 8 text

Reações <- Do time!

Slide 9

Slide 9 text

Callbacks são úteis

Slide 10

Slide 10 text

Callbacks são úteis Quando são simples. $(‘.btn’).click(function(){ $(‘.text’).color(‘#FF0000’); });

Slide 11

Slide 11 text

Callbacks são úteis

Slide 12

Slide 12 text

Callbacks são úteis Mas qualquer coisa além disso, torna-se complexo fazer coisas simples. app.put('/todos/:id', function(req, res){ //Código em Node.JS para update no MongoDB getTodosCollection().findById(req.params.id, function(err, item){ if(err) res.send(500, ‘Erro ao atualizar os dados’); else { todo = item; todo.completed = req.body.completed; getTodosCollection().save(todo, function(err, item){ if(err) res.send(500, ‘Erro ao atualizar os dados’); else res.send(item); }); } }); });

Slide 13

Slide 13 text

Mas existe solução? Promises Functional Reactive Programming (FRP) SIM!!!

Slide 14

Slide 14 text

Promises A promise represents the eventual value returned from the single completion of an operation. http:/ /wiki.commonjs.org/wiki/Promises/A

Slide 15

Slide 15 text

Promises - Interface .then(fulfilledHandler, errorHandler, progressHandler) .state() .resolve(value) .reject(error)

Slide 16

Slide 16 text

Promises - state Unfulfilled Fulfilled Failed

Slide 17

Slide 17 text

Promises - State Unfulfilled

Slide 18

Slide 18 text

Promises - State Unfulfilled Fulfilled

Slide 19

Slide 19 text

Promises - State Unfulfilled Fulfilled Failed

Slide 20

Slide 20 text

Promises - State Unfulfilled Fulfilled Failed Isso ocorre somente uma vez!

Slide 21

Slide 21 text

$.Deferred Promises no jQuery

Slide 22

Slide 22 text

$.Deferred $.get('/twitter?q=' + query) .then( function(result) { ... }, function(error) { ... } );

Slide 23

Slide 23 text

$.Deferred var asyncOp = function(){ var deferred = $.Deferred(); setTimeout(function(){ deferred.resolve('done'); }, 1000); return deferred.promise(); };

Slide 24

Slide 24 text

$.Deferred var asyncOp = function(){ var deferred = $.Deferred(); setTimeout(function(){ deferred.reject('error'); }, 1000); return deferred.promise(); };

Slide 25

Slide 25 text

$.Deferred - Continuations $.ajax(....) ! .then(function(resultado){ ! / /faz alguma coisa com resultado ! return $.ajax(...); / /outra ação async ! }) ! .then(function(outroResultado){ ! / /faz outra coisa com outro resultado ! }) ! .fail(function(erro){ ! / /erro caso qualquer operação falhe ! });

Slide 26

Slide 26 text

$.Deferred - when var d1 = $.get('search.twitter.com/search.json?q=TDC2013'); var d2 = $.get('search.twitter.com/search.json?q=Floripa'); var d3 = $.get('search.twitter.com/search.json?q=Javascript'); $.when(d1, d2, d3) .done(function(tdc, floripa, jurere){ ... });

Slide 27

Slide 27 text

Functional Reactive Programming Tratando eventos Like a Boss com Reactive Extensions (Rx)

Slide 28

Slide 28 text

Na maior parte do tempo estamos reagindo ao ambiente

Slide 29

Slide 29 text

Dados de location (GPS) Push notifications (web sockets, twitter, etc.) Eventos complexos de UI

Slide 30

Slide 30 text

Iterator x Observer interface IEnumerable { ! IEnumerator GetEnumerator(); } interface IEnumerator { ! bool MoveNext(); / / throws Exception ! T Current { get; } }

Slide 31

Slide 31 text

Iterator x Observer interface IObservable { ! IEnumerator GetEnumerator(); } interface IEnumerator { ! bool MoveNext(); / / throws Exception ! T Current { get; } }

Slide 32

Slide 32 text

Iterator x Observer interface IObservable { ! IEnumerator GetEnumerator(); } interface IObserver { ! bool MoveNext(); / / throws Exception ! T Current { get; } }

Slide 33

Slide 33 text

Iterator x Observer interface IObservable { ! void Subscribe(IObserver observer) } interface IObserver { ! bool MoveNext(); / / throws Exception ! T Current { get; } }

Slide 34

Slide 34 text

Iterator x Observer interface IObservable { ! void Subscribe(IObserver observer) } interface IObserver { ! void OnNext(T item) ! T Current { get; } }

Slide 35

Slide 35 text

Iterator x Observer interface IObservable { ! void Subscribe(IObserver observer) } interface IObserver { ! void OnNext(T item) ! void OnError(Exception ex) }

Slide 36

Slide 36 text

Iterator x Observer interface IObservable { ! void Subscribe(IObserver observer) } interface IObserver { ! void OnNext(T item) ! void OnError(Exception ex) void OnCompleted() }

Slide 37

Slide 37 text

O verdadeiro poder do Rx filtros (where, distinct, skip, take, all, any) agregações (count, min, max, avg, sum, aggregate, scan) Transformações (map, flatMap) Combinações (concat, merge, zip) Schedulers You don’t know the power of Rx (yet)

Slide 38

Slide 38 text

Fatality var sequencia = [ 38, / / up 38, / / up 40, / / down 40, / / down 37, / / left 39, / / right 37, / / left 39, / / right 66, / / b 65 / / a ];

Slide 39

Slide 39 text

Fatality Rx.Observable.fromEvent(document, 'keyup') .select(function (e) { return e.keyCode; / / pega o keycode }) .bufferWithCount(10) / / ultimos 10 .where(function (input) { return arrayEquals(sequencia, input); }) / / sequencia correta .subscribe(function () { alert('FATALITY!'); / / FATALITY! });

Slide 40

Slide 40 text

Mouse drag var mouseDown = Rx.Observable .fromEvent(canvas, 'mousedown') var mouseMove = Rx.Observable .fromEvent(canvas, 'mousemove') .map(function(e){ return getInputCoordinates(e); }); var mouseUp = Rx.Observable .fromEvent(canvas, 'mouseup');

Slide 41

Slide 41 text

Mouse drag var mouseDrag = mouseMove .skipUntil(mouseDown) .takeUntil(mouseUp); mouseDrag.subscribe(function(coordinates){ ... })

Slide 42

Slide 42 text

Quem usa? Netflix - Usado para serviços internos assíncronos. Escrito em Java Github - Cliente para Windows (C#) e Mac (Objective-C) SQL Server Stream Insight

Slide 43

Slide 43 text

Open-Source http:/ /rx.codeplex.com/ (.NET, JS, C++) https:/ /github.com/Netflix/RxJava (Java, Scala, Groovy, Clojure, JRuby) https:/ /github.com/ReactiveCocoa/ ReactiveCocoa (Objective-C)

Slide 44

Slide 44 text

Aprenda mais http:/ /www.introtorx.com (C#) http:/ /channel9.msdn.com/tags/Rx/ http:/ /rxwiki.wikidot.com/101samples http:/ /csl.stanford.edu/~christos/pldi2010.fit/ meijer.duality.pdf (Paper do Erik Meijer sobre dualidade de IEnumerable x IObservable)

Slide 45

Slide 45 text

http:/ /dnad.azurewebsites.net/

Slide 46

Slide 46 text

No content

Slide 47

Slide 47 text

Perguntas?

Slide 48

Slide 48 text

Obrigado breno_ferreira [email protected] Aproveitem o evento! Inscrevam-se no DNAD!

Slide 49

Slide 49 text

No content