-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
877 lines (778 loc) · 26.9 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Applause - HTML presentations powered by AngularJS</title>
<meta name="description" content="HTML presentations powered by Angular JS">
<meta name="viewport" content="width=device-width">
<!-- build:css assets/styles/applause.css -->
<link rel="stylesheet" href="assets/styles/main.css">
<!-- endbuild -->
<link rel="stylesheet" href="assets/theme/default.css">
<!-- Chrome print bug. Credits to @hakimel http://goo.gl/rGoUvj -->
<script>
if( window.location.search.match(/pdf/gi) ) {
var link = document.createElement('link');
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = 'assets/styles/pdf.css';
document.getElementsByTagName('head')[0].appendChild(link);
}
</script>
</head>
<body ng-app="applauseApp" ng-keyup="keyup($event)">
<div id="presentation" ng-controller="DeckCtrl" ng-cloak>
<goto class="ph"></goto>
<div class="container">
<!-- =========== SLIDE =========== -->
<slide>
<div class="abs-center">
<h1>Async & Me</h1>
<h3>My story with asynchronous programming</h3>
<img class="center" src="assets/theme/images/MM_logo.png"/>
</div>
</slide>
<slide>
<div class="abs-center">
<h2>Matteo Scandolo</h2>
<img class="round center" src="assets/images/teo.jpg" height="200" width="200">
<h3>Frontend Leader @LinkMe</h3>
<h3>Co-Founder @MeanMilan</h3>
</div>
</slide>
<slide>
<h2>Why Async Handling is so important in JS?</h2>
<img class="center" src="assets/theme/images/event-loop.jpg" height="250" alt="">
<code prism class="language-javascript">
while(queue.waitForMessage()){
queue.processNextMessage();
}
</code>
<note>Event Loop!</note>
</slide>
<slide>
<div class="abs-center">
<h1>Disclaimer</h1>
<h3>This is not about a framework</h3>
<h3>This is not the truth, <br> it's my experience</h3>
</div>
</slide>
<slide steps="1">
<h1 class="abs-center">The Past</h1>
<div step="1">
<h2>Callbacks</h2>
</div>
</slide>
<slide>
<h1>What is a Callback? </h1>
<h4>
In JavaScript, functions are considered first-class citizens, <br> they are able to be passed as arguments or stored in variables or fields.
</h4>
<h3>
Callbacks are functions that are passed as an argument to another function.
</h3>
<code prism class="language-javascript">
function runThisFunction(myCallbackFunction) {
myCallbackFunction();
}
runThisFunction(function() {
console.log('Kind of useless, but I see your point.');
});
</code>
</slide>
<slide steps="2">
<h2>Why I do need a callback?</h2>
<div class="abs-center">
<div step="1">
<h3>Allow the calling code to encapsulate some logic</h3>
</div>
<div step="2">
<h3>Logic to be performed after an asynchronous operation</h3>
</div>
</div>
</slide>
<slide>
<h2>A common example</h2>
<code prism class="language-javascript">
$.ajax({
url: '/api/',
type: 'GET',
success: function(data) {
// Our callback function; this will be executed
// after the async query is finished
}
});
</code>
</slide>
<slide steps="1">
<h2>Pretty simple, but what's next?</h2>
<div step="1">
<code prism class="language-javascript">
asyncFn1(function(){
asyncFn2(function(){
asyncFn3(function(){
asyncFn4(function(){
asyncFn5(function(){
...
})
})
})
})
})
</code>
</div>
</slide>
<slide bg-img="fire-orange-emergency-burning.jpg" credits="http://www.pexels.com/">
<h1 class="abs-center">Welcome to Callback Hell!</h1>
</slide>
<slide steps="4">
<h2>Ok, the term is cool but what are the problems?</h2>
<div step="1">
<h3>Unexpressive</h3>
</div>
<div step="2">
<h3>Unmaintanable</h3>
</div>
<div step="3">
<h3>Untestable</h3>
</div>
<div step="4">
<h2>Can we emprove this?</h2>
</div>
</slide>
<slide>
<h2>Named Functions</h2>
<code prism class="language-javascript">
function asyncFn3(res){
//do async stuff
}
function asyncFn2(res){
//do async stuff
asyncFn3(data);
}
function asyncFn1(input){
//do async stuff
asyncFn2(res);
}
asyncFn1(initialData);
</code>
</slide>
<slide steps="3">
<h2>Better but...</h2>
<div step="1">
<h3>Function(s) are referenced with other function(s)</h3>
</div>
<div step="2">
<h3>Following the business logic is difficult</h3>
</div>
<div step="3">
<h3>Add/remove steps can have side effects</h3>
</div>
</slide>
<slide steps="8">
<h2>Anyway...</h2>
<div step="1">
<h3>Libraries can help!</h3>
</div>
<div step="2">
<h3><a href="https://github.com/caolan/async">async</a></h3>
</div>
<div class="col half">
<div step="3">
<h3 class="small">.each(arr, iterator, cb)</h3>
</div>
<div step="5">
<h3 class="small">.series(arr, cb)</h3>
</div>
<div step="7">
<h3 class="small">.map(arr, iterator, cb)</h3>
</div>
</div>
<div class="col half">
<div step="4">
<h3 class="small">.all(arr, iterator, cb)</h3>
</div>
<div step="6">
<h3 class="small">.parallel(tasks, cb)</h3>
</div>
<div step="8">
<h3 class="small">.reduce(arr, memo, iterator, cb)</h3>
</div>
</div>
<note>
.each -> array di parametri, applica una fn async
.all -> ritorna true se tutto arr passa il test async iterator
</note>
</slide>
<slide>
<h2 class="abs-center">
Can we do better?
</h2>
</slide>
<slide bg-img="promise-land.jpg"></slide>
<slide steps="1">
<h2>A promise represents the eventual result of an asynchronous operation.</h2>
<div step="1">
<div class="separator"></div>
<h2>In practice something that have a <code class="inline">.then</code> method</h2>
</div>
</slide>
<slide>
<h2>A common example:</h2>
<code prism class="language-javascript">
Resource.query()
.then(
function(res){
// successHandles
},
function(e){
// errorHandler
}
);
</code>
<h3>From AngularJs Resources</h3>
</slide>
<slide steps="7">
<h2>Promise States</h2>
<div step="1" class="col third">
<h3><code class="inline">pending</code></h3>
</div>
<div step="2" class="col third">
<h3><code class="inline">fulfilled</code></h3>
</div>
<div step="3" class="col third">
<h3><code class="inline">rejected</code></h3>
</div>
<div step="4">
<h2>Promise Features</h2>
</div>
<div class="col half">
<div step="5">
<h3>Once fullfilled/rejected state and value does NOT change</h3>
</div>
</div>
<div class="col half">
<div step="6">
<h3><code class="inline">.then</code> MUST retutn a Promise</h3>
</div>
<div step="7">
<h3><code class="inline">.then</code> are chainables</h3>
</div>
</div>
</slide>
<slide steps="5">
<h2>Promise Methods</h2>
<div step="1" class="col half">
<h3><code class="inline">.then(success, error)</code></h3>
</div>
<div step="2" class="col half">
<h3><code class="inline">.catch(error)</code></h3>
</div>
<div step="3">
<h3><code class="inline">[.finally(done)]</code></h3>
</div>
<div step="4" class="col half">
<h3><code class="inline">.all(promiseArray)</code></h3>
</div>
<div step="5" class="col half">
<h3><code class="inline">.race(promiseArray)</code></h3>
</div>
<note>finaly is provided from libraries</note>
</slide>
<slide>
<h2>Promise declaration: ES6</h2>
<code prism class="language-javascript">
let promise = new Promise(resolve, reject){
// do async stuff
// if success
resolve(value);
// if error
reject(e);
};
</code>
<code prism class="language-javascript">
// use the promise
promise.then(successHandler, errorHandler);
</code>
<note>
Error must be handled inside the promise
Babel supports promise
</note>
</slide>
<slide>
<h2>Promise declaration: Q - $q</h2>
<code prism class="language-javascript">
var Q = require('q');
var promise = function(){
var deferred = Q.defer();
FS.readFile("foo.txt", "utf-8", function (error, text) {
if (error) {
deferred.reject(new Error(error));
} else {
deferred.resolve(text);
}
});
return deferred.promise;
};
</code>
<code prism class="language-javascript">
// use the promise
promise.then(successHandler, errorHandler);
</code>
</slide>
<slide>
<h2>Promise declaration: BlueBird</h2>
<code prism class="language-javascript">
var P = require('bluebird');
var promise = P.promisify(function(done){
// do async stuff
// if error
done(e);
// if success
done(null, value);
});
</code>
<code prism class="language-javascript">
var promise = P.promisify(
function(itemId, done){
return Model.findById(itemId, done);
}
);
</code>
<note>Rock with node!</note>
</slide>
<slide>
<h2>Promise Chains</h2>
<code prism class="language-javascript">
let pr1 = function(){
return new Promise(resolve, reject){...}
};
// let pr2, pr3, prN, ...
pr1()
.then(function(res){
return pr2;
})
.then(function(res){
return pr3;
})
.then(function(res){
// do something with the result
})
</code>
<note>Remember CB Hell slide 9?</note>
</slide>
<slide>
<h2>A practical example</h2>
<code prism class="language-javascript">
// Post and Comments are ngResources, they return a promise
Post.get(postId)
.then((post) => {
$scope.post = post;
return Comments.query({postId: post._id});
})
.then((comments) => {
$scope.post.comments = comments;
})
.catch(function(err){
$scope.error = err.data.message;
})
.finally(() => {
$scope.loader = false;
})
</code>
</slide>
<slide steps="3">
<h2>Promise advantages</h2>
<div step="1">
<h3>Function(s) are separated (dillo a parole tue)</h3>
</div>
<div step="2">
<h3>Following the business logic is easy</h3>
</div>
<div step="3">
<h3>Add/remove steps with no pain!</h3>
</div>
</slide>
<slide>
<h2>Handling Errors</h2>
<code prism class="language-javascript">
pr1()
.then(
function(res){
// do stuff
},
function(err){
// handle error
}
);
</code>
</slide>
<slide>
<h2 class="abs-center">
If a promise is reject the chain is skipped untill the first error handler
</h2>
</slide>
<slide>
<h2>Handling Errors</h2>
<code prism class="language-javascript">
pr1()
.then(
function(res){
// do stuff (if pr1 is resolved)
return pr2();
},
function(err){
// handle error from pr1
}
)
.then(
function(res){
// do stuff (if pr2 is resolved) else this is never called
},
function(err){
// handle error from pr2
}
);
</code>
</slide>
<slide>
<h1 class="abs-center">Practical Advice</h1>
</slide>
<slide steps="2">
<h2>Use <code class="inline">.catch</code></h2>
<div class="col half">
<code prism class="language-javascript">
pr1()
.then(function(res){
// this is not executed
// if pr1 is rejected
return pr2();
})
.catch(function(err){
//handle error
});
</code>
<div step="2">
<h3><code class="inline">.catch</code> emproves readability</h3>
</div>
</div>
<div class="col half" step="1">
<code prism class="language-javascript">
pr1()
.catch(function(err){
//handle error
})
.then(function(res){
// this is executed both if
// pr1 is resolved
// or rejected
return pr2();
})
.catch(function(err){
//handle error
});
</code>
</div>
</slide>
<slide>
<h2>Passing multiple values: ES6</h2>
<code prism class="language-javascript">
function timeout(duration = 0) {
return new Promise((resolve, reject) => {
setTimeout(function(){
return resolve(['a','b','c']);
}, duration);
})
}
var p = timeout(500)
.then((res) => {
let [a, b, c] = res;
console.log(a, b, c);
});
</code>
<note>Destructuring</note>
</slide>
<slide>
<h2>Passing multiple values: Bluebird</h2>
<code prism class="language-javascript">
var P = require('bluebird');
var pr = P.promisify(function(timeout,done){
setTimeout(function() {
done(null, ['a','b', 'c']);
}, 10);
});
pr(500)
.spread(function(a,b,c){
console.log(a, b, c);
});
</code>
</slide>
<slide>
<h2>Execute a promises in parallel</h2>
<code prism class="language-javascript">
function timeout(duration = 0) {
return new Promise((resolve, reject) => {
setTimeout(function(){
return resolve(duration);
}, duration);
})
}
Promise.all([timeout(500), timeout(800), timeout(300)])
.then(values => {
console.log(values); // [500, 800, 300]
});
</code>
</slide>
<!-- <slide>
<h2>Execute a promises in series</h2>
<code prism class="language-javascript">
function timeout(duration = 0) {
return new Promise((resolve, reject) => {
setTimeout(function(){
return resolve(duration);
}, duration);
})
}
[timeout(500), timeout(800), timeout(300)].reduce(function(sequence, promise) {
return promise
.then((res) => {
console.log(res);
});
}, Promise.resolve());
</code>
</slide> -->
<slide steps="1">
<h2>Break a promise chain</h2>
<code prism class="language-javascript">
pr()
.then(...)
.then(function(res){
throw new Error(...):
})
.then(...)
.then(...)
.then(...)
.catch(...)
</code>
<div step="1">
<h3>You should handle the error!</h3>
</div>
</slide>
<slide steps="1">
<h2>Moving from callbacks to promises?</h2>
<div step="1">
<code prism class="language-javascript">
function(foo, bar, done){
if(typeof done !== 'function'){
// return a promise
var deferred = Q.defer();
done = function(err, res){
if(err){
return deferred.reject(err);
}
return deferred.resolve(res);
};
}
return done(err, res);
}
</code>
</div>
</slide>
<slide steps="2">
<h2>Could be simpler?</h2>
<div step="1">
<code prism class="language-javascript">
var cbFunc = function(foo, bar, done){
// do stuff
done(err, res);
};
cbFunc('a', 'b', callback);
</code>
</div>
<div step="2">
<code prism class="language-javascript">
var P = require('bluebird');
var promisified = P.promisify(cbFunc);
promisified('a','b')
.then(...)
</code>
</div>
</slide>
<!-- <slide steps="2">
<h2>Mixing Sync and Async Methods</h2>
<div step="1">
<h1>Don't do that! It hurts!</h1>
</div>
<div step="2">
<h3>If the method have 1% possibilities to get Async, start with async!</h3>
</div>
</slide> -->
<slide>
<h2>Suggested Readings:</h2>
<h3>https://promisesaplus.com</h3>
<h4>https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise</h4>
<h4>http://www.html5rocks.com/en/tutorials/es6/promises/</h4>
</slide>
<slide steps="1">
<h1 class="abs-center">The Future</h1>
<div step="1">
<h2>Generators</h2>
</div>
</slide>
<slide steps="1">
<h2>What are generators?</h2>
<div step="1">
<h1 class="abs-center">A brand new type of functions</h1>
</div>
</slide>
<slide steps="2">
<h2>What is different?</h2>
<div step="1">
<h1 class="abs-center">Run to completion</h1>
</div>
</slide>
<slide>
<h2>What does it means?</h2>
<code prism class="language-javascript">
setTimeout(function(){
console.log("Hello World");
},1);
function foo() {
// NOTE: don't ever do crazy long-running loops like this
for (var i=0; i<=1E10; i++) {
console.log(i);
}
}
foo();
// 0..1E10
// "Hello World"
</code>
</slide>
<slide steps="2">
<h2>Generators</h2>
<div step="1">
<h3>Run, Stop, Run!</h3>
</div>
<div step="2">
<code prism class="language-javascript">
function *foo() {
yield 1;
return 2;
}
var it = foo();
var message = it.next();
console.log(message); // { value:1, done:false }
console.log( it.next() ); // { value:2, done:true }
</code>
</div>
</slide>
<slide steps="1">
<h2>Can we <code class="inline">yield</code> a promise?</h2>
<div step="1">
<code prism="" class="language-javascript">
function request(url) {
makeAjaxCall( url, function(response){
it.next( response );
} );
}
function *main() {
var result1 = yield request( "http://some.url.1" );
var data = JSON.parse( result1 );
var result2 = yield request( "http://some.url.2?id=" + data.id );
var resp = JSON.parse( result2 );
console.log( "The value you asked for: " + resp.value );
}
var it = main();
it.next(); // get it all started
</code>
<span>http://davidwalsh.name/async-generators</span>
</div>
</slide>
<slide steps="1">
<h2>Bluebird <code class="inline">.coroutine</code> is here!</h2>
<div step="1">
<code prism="" class="language-javascript">
P.coroutine(function*(){
let pr1 = yield promise1();
let pr2 = yield promise2();
let pr3 = yield promise3();
// here is my then
})()
.catch(function(err){
// handle error
});
</code>
</div>
<note>
Ricordati di chiamare la funzione!!!
</note>
</slide>
<slide steps="2">
<h2>What's next?</h2>
<div step="1">
<h1>Async ... Await</h1>
</div>
<div step="2" style="margin-top: 100px;">
<code prism class="language-javascript">
(async function() {
let res = await AsyncFunction();
// now res is available
}());
</code>
</div>
</slide>
<slide steps="2">
<div step="1">
<h1>Thanks!</h1>
</div>
<div step="2">
<h1 class="abs-center">Questions?</h1>
</div>
<div step="1">
<h4>@_teone</h4>
</div>
</slide>
<!-- TODO
Callbacks are just blocks of code which can be run in response to events such as as timers going off or messages being received from the server. Any function can be a callback, and every callback is a function.
Promises are objects which store information about whether or not those events have happened yet, and if they have, what their outcome is.
http://jamesknelson.com/grokking-es6-promises-the-four-functions-you-need-to-avoid-callback-hell/
http://jamesknelson.com/grokking-es6-promises.png
REDUCE an array - run promise in series
.curry
break a promise chains
Generators
Coroutine Bluebird
Examples Node / Tests -->
<!-- =========== /SLIDE =========== -->
</div>
<flip-clock></flip-clock>
<div id="slide-count" ng-show="{{isSlideCountVisible}}">{{$storage.currentSlide}}/{{lastSlide}}</div>
<progress-bar class="ph" ng-show="{{isProgressBarVisible}}"></progress-bar>
</div>
<!-- build:js assets/scripts/applause.js -->
<script src="assets/scripts/vendor/prism.js"></script>
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/json3/lib/json3.js"></script>
<script src="bower_components/angular-animate/angular-animate.js"></script>
<script src="bower_components/showdown/src/showdown.js"></script>
<script src="bower_components/angular-sanitize/angular-sanitize.js"></script>
<script src="bower_components/ngstorage/ngStorage.js"></script>
<script src="bower_components/moment/moment.js"></script>
<script src="assets/scripts/app.js"></script>
<script src="config.js"></script>
<script src="assets/scripts/controllers/deck.js"></script>
<script src="assets/scripts/directives/slide.js"></script>
<script src="assets/scripts/directives/fit.js"></script>
<script src="assets/scripts/directives/progressbar.js"></script>
<script src="assets/scripts/services/appdata.js"></script>
<script src="assets/scripts/directives/markdown.js"></script>
<script src="assets/scripts/directives/bg-img.js"></script>
<script src="assets/scripts/directives/goto.js"></script>
<script src="assets/scripts/directives/flip-clock.js"></script>
<script src="assets/scripts/directives/prism.js"></script>
<script src="assets/scripts/directives/note.js"></script>
<script src="assets/scripts/directives/step.js"></script>
<!-- endbuild -->
</body>
</html>