-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
967 lines (885 loc) · 23.5 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
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>Async Javascript</title>
<script src="https://use.typekit.net/dkq5epu.js"></script>
<script>try{Typekit.load({ async: true });}catch(e){}</script>
<link rel="stylesheet" href="css/reveal.css">
<link rel="stylesheet" href="css/theme/kaliber5.css">
<link rel="stylesheet" href="css/spinner.css">
<link rel="stylesheet" href="css/custom.css">
<!-- Printing and PDF exports -->
<script>
var link = document.createElement( 'link' );
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = window.location.search.match( /print-pdf/gi ) ? 'css/print/pdf.css' : 'css/print/paper.css';
document.getElementsByTagName( 'head' )[0].appendChild( link );
</script>
</head>
<body>
<div class="reveal">
<div class="slides">
<section>
<h1>Async Javascript</h1>
<h2>Callbacks, Promises, Async/Await</h2>
<div class="floatingBarsG">
<div class="blockG rotateG_01"></div>
<div class="blockG rotateG_02"></div>
<div class="blockG rotateG_03"></div>
<div class="blockG rotateG_04"></div>
<div class="blockG rotateG_05"></div>
<div class="blockG rotateG_06"></div>
<div class="blockG rotateG_07"></div>
<div class="blockG rotateG_08"></div>
</div>
</section>
<section>
<div class="id-card">
<dl>
<dt>Name</dt>
<dd>Andreas Schacht</dd>
<dt>Company</dt>
<dd><a href="http://www.kaliber5.de">kaliber5</a></dd>
<dt>Job title</dt>
<dd>Web Developer</dd>
<dt>Email</dt>
<dd><a href="mailto:schacht@kaliber5.de">schacht@kaliber5.de</a></dd>
</dl>
</div>
<aside class="notes">
Oh hey, these are some notes. They'll be hidden in your presentation, but you can see them if you open the
speaker notes window (hit 's' on your keyboard).
</aside>
</section>
<section data-markdown>
<script type="text/template">
## TOC
what will I talk about
- sync example
- callback example
- promise example
- async/await example
- async with generators
Note:
- example covers a common use case
</script>
</section>
<section data-markdown>
<script type="text/template">
#### Sync
```js
const fs = require('fs');
const html = require('./html');
function mdToHtml(file) {
let markdown = fs.readFileSync(file);
let htmlContent = html.fromMarkdownSync(markdown);
fs.writeFileSync(`${file}.html`, htmlContent);
}
mdToHtml('./README.md');
console.log('done');
```
<p class="fragment fade-left">Missing error handling</p>
Note:
- very common use case
- next process depends on result of previous one
- replace operations by any other
- advantage
- good readability
- easy to see, what happens
</script>
</section>
<section data-markdown>
<script type="text/template">
#### Sync
```js
const fs = require('fs');
const html = require('./html');
function mdToHtml(file) {
let markdown = fs.readFileSync(file);
let htmlContent = html.fromMarkdownSync(markdown);
fs.writeFileSync(`${file}.html`, htmlContent);
}
try {
mdToHtml('./README.md');
console.log('done');
} catch(err) {
console.error(err);
}
```
Note:
- surround function call
- advantage
- try/catch works well in sync context
- disadvantage
- blocking code
- time consuming processes
</script>
</section>
<section>
<div class="floatingBarsG">
<div class="blockG rotateG_01"></div>
<div class="blockG rotateG_02"></div>
<div class="blockG rotateG_03"></div>
<div class="blockG rotateG_04"></div>
<div class="blockG rotateG_05"></div>
<div class="blockG rotateG_06"></div>
<div class="blockG rotateG_07"></div>
<div class="blockG rotateG_08"></div>
</div>
<aside class="notes">
result<br/>
you know what i mean
</aside>
</section>
<section data-markdown>
<script type="text/template">
#### Callbacks
```js
const fs = require('fs');
fs.readFile('./README.md', (err, data) => {
// executes after data is available
});
```
<p class="fragment fade-left">"error-first"- / "errback"-convention</p>
<p class="fragment fade-left">err is null on success</p>
Note:
- pass a function, that receives 2 arguments
- common convention in node
- well known
- signature is just a convention
</script>
</section>
<section data-markdown>
<script type="text/template">
## Callbacks
```js
const fs = require('fs');
fs.readFile('./README.md', (err, data) => {
if (err) {
// handle error
} else {
// process data
}
});
```
Note:
- endup to a construct like this
</script>
</section>
<section data-markdown>
<script type="text/template">
## Callbacks
```js
const fs = require('fs');
try {
fs.readFile('./README.md', (err, data) => {
if (err) {
throw err;
}
console.log('done');
});
} catch(err) {
console.error(err);
}
```
<p class="fragment fade-left">try / catch won't work</p>
<p class="fragment fade-left">already leave the try block</p>
</script>
</section>
<section data-markdown>
<script type="text/template">
#### Callbacks
Welcome to...
```js
const fs = require('fs');
const html = require('./html');
function mdToHtml(file, cb) {
fs.readFile(file, (err, markdown) => {
html.fromMarkdownCb(markdown, (err, htmlContent) => {
fs.writeFile(`${file}.html`, htmlContent, (err) => {
cb(null);
});
});
});
}
mdToHtml('./README.md', (err) => {
console.log('done');
});
```
<p class="fragment fade-left">...callback hell</p>
Note:
- phrase: callback hell
- phrase: pyramid of doom
- shape of pyramid
- guess, what it means
- harder to read
- indentation
- nested level 3
- not finished yet
- handle errors
</script>
</section>
<section data-markdown class="md-small md-code-large">
<script type="text/template">
#### Callbacks
```js
const fs = require('fs');
const html = require('./html');
function mdToHtml(file, cb) {
fs.readFile(file, (err, markdown) => {
if (err) {
cb(err);
} else {
html.fromMarkdownCb(markdown, (err, htmlContent) => {
if (err) {
cb(err);
} else {
fs.writeFile(`${file}.html`, htmlContent, (err) => {
if (err) {
cb(err);
} else {
cb(null);
}
});
}
});
}
});
}
mdToHtml('./README.md', (err) => {
if (err) {
console.error(err);
} else {
console.log('done');
}
});
```
<p class="fragment fade-left">exit as soon as possible</p>
Note:
- phrase: callback hell
- shape of pyramid
- known as pyramid of doom
- very hard to read
- reduce indentation, be more shallowed
- exit as soon as possible
</script>
</section>
<section data-markdown class="md-small md-code-large">
<script type="text/template">
#### Callbacks
```js
const fs = require('fs');
const html = require('./html');
function mdToHtml(file, cb) {
fs.readFile(file, (err, markdown) => {
if (err) {
return cb(err);
}
html.fromMarkdownCb(markdown, (err, htmlContent) => {
if (err) {
return cb(err);
}
fs.writeFile(`${file}.html`, htmlContent, (err) => {
if (err) {
return cb(err);
}
cb(null);
});
});
});
}
mdToHtml('./README.md', (err) => {
if (err) {
return console.error(err);
}
console.log('done');
});
```
<p class="fragment fade-left">use named functions</p>
Note:
- skip else block
- skip further execution by return statement
- what we can do
- use named function
- error pop up
- stack trace
</script>
</section>
<section data-markdown class="md-small md-code-large">
<script type="text/template">
## Callbacks
```js
const fs = require('fs');
const html = require('./html');
function mdToHtml(file, cb) {
fs.readFile(file, (err, markdown) => {
if (err) {
return cb(err);
}
htmlFromMd(markdown, file, cb);
});
}
function htmlFromMd(markdown, file, cb) {
html.fromMarkdownCb(markdown, (err, htmlContent) => {
if (err) {
return cb(err);
}
writeFile(htmlContent, file, cb);
}
function writeFile(htmlContent, file, cb) {
fs.writeFile(`${file}.html`, htmlContent, (err) => {
if (err) {
return cb(err);
}
cb(null);
});
}
mdToHtml('./README.md', (err) => {
if (err) {
return console.error(err);
}
console.log('done');
});
```
Note:
- better indentation
- more shallowed
- drawback, disadvantage
- nested level is still the same
- missing chaining
- compare
- far away from first example
- not really intuitive like the first one
- comparision to sync
</script>
</section>
<section data-markdown>
<script type="text/template">
#### Sync
```js
const fs = require('fs');
const html = require('./html');
function mdToHtml(file) {
let markdown = fs.readFileSync(file);
let htmlContent = html.fromMarkdownSync(markdown);
fs.writeFileSync(`${file}.html`, htmlContent);
}
try {
mdToHtml('./README.md');
console.log('done');
} catch(err) {
console.error(err);
}
```
Note:
- Advantage of callback
- its async
</script>
</section>
<section data-markdown>
<script type="text/template">
## Promises
- objects represents an eventual result
- primary interacting through its `then` method
- states
- pending
- fullfilled
- rejected
- settled = fullfilled || rejected
Note:
- also well known
</script>
</section>
<section data-markdown>
<script type="text/template">
#### Promises
```js
let promise = new Promise((resolve, reject) => {
// do something time consuming
// on success
resolve(value);
// on failure
reject(reason);
});
promise.then((value) => {
// on fulfillment
}, (reason) => {
// on rejection
});
```
Note:
- constructor takes a callback
- passed 2 functions into the callback
- then takes 2 arguments: onFulfill/onReject(fulfill/reject)
- then returns a promise
</script>
</section>
<section data-markdown>
<script type="text/template">
## Promises
#### chainable
```js
promise.then((data) => {
return new Promise(...);
}).then((data) => {
return 42;
}).then((data) => {
throw new Error('message');
}).then((data) => {
// this will never been reached
}).then(undefined, (error) => {
// handle error;
});
```
Note:
- return promises
- return values
- throw error
- see last then
</script>
</section>
<section data-markdown>
<script type="text/template">
## Promises
#### chainable
```js
promise.then((data) => {
return new Promise(...);
}).then((data) => {
return 42;
}).then((data) => {
throw new Error('message');
}).then((data) => {
// this will never been reached
}).catch((error) => {
// handle error;
});
```
Note:
- catch method
- familar with proms
- point out one thing
</script>
</section>
<section data-markdown>
<script type="text/template">
## Promises
...swallow errors.
Do they really?
```js
let promise = promise.then((data) => {
throw new Error('message');
});
// ...some more code
```
...what happens now?
Note:
- not popped up, immediatly
- promise is in rejected state
- there are 2 options
</script>
</section>
<section data-markdown>
<script type="text/template">
## Promises
You can chain the catch later
```js
let promise = promise.then((data) => {
throw new Error('message');
});
//
// ...in another (maybe async) part of code
//
promise.catch((error) => {
console.error(error);
});
```
Note:
- As long as the promise live
- and is accessable / has a reference
- add something to the chain
</script>
</section>
<section data-markdown>
<script type="text/template">
## Promises
don't really swallow errors...
```js
let promise = promise.then((data) => {
throw new Error('message');
});
//
// ...promise is settled and not referenced anymore...
// ...the error will popup on garbage-collection
```
Note:
- hard to say when
- don't forget to catch
</script>
</section>
<section data-markdown>
<script type="text/template">
## Promises
#### wrap callback style
```js
const fs = require('fs');
fs.readFile('./README.md', (err, data) => {
if (err) {
// handle error
} else {
// process data
}
});
```
Note:
- callback style is still common
- from previous explaination
</script>
</section>
<section data-markdown>
<script type="text/template">
## Promises
#### wrap callback style
```js
const fs = require('fs');
let promise = new Promise((resolve, reject) => {
fs.readFile('./README.md', (err, data) => {
if (err) {
return reject(err);
}
resolve(data);
});
});
promise.then((data) => {
// will be called, if promise resolves
}).catch((err) => {
// will be called, when promise rejects
});
```
Note:
- back to example
</script>
</section>
<section data-markdown>
<script type="text/template">
#### Promises
```js
const fsp = require('fs-promise');
const html = require('./html');
function mdToHtml(file) {
return fsp.readFile(file)
.then((markdown) => {
return html.fromMarkdownProm(markdown);
}).then((htmlContent) => {
return fsp.writeFile(`${file}.html`, htmlContent);
});
}
mdToHtml('./README.md').then(() => {
console.log('done');
}).catch((error) => {
console.error(error);
});
```
Note:
- see the chance
- a little bit shorter
- fs ops also available as promises
</script>
</section>
<section data-markdown>
<script type="text/template">
#### Promises
```js
const fsp = require('fs-promise');
const html = require('./html');
function mdToHtml(file) {
return fsp.readFile(file)
.then(html.fromMarkdownProm)
.then((htmlContent) => {
return fsp.writeFile(`${file}.html`, htmlContent);
});
}
mdToHtml('./README.md').then(() => {
console.log('done');
}).catch((error) => {
console.error(error);
});
```
Note:
- close to the sync one
- comparison
</script>
</section>
<section data-markdown>
<script type="text/template">
#### Sync
```js
const fs = require('fs');
const html = require('./html');
function mdToHtml(file) {
let markdown = fs.readFileSync(file);
let htmlContent = html.fromMarkdownSync(markdown);
fs.writeFileSync(`${file}.html`, htmlContent);
}
try {
mdToHtml('./README.md');
console.log('done');
} catch(err) {
console.error(err);
}
```
Note:
- good, but not satisfied
- have another bullet
</script>
</section>
<section data-markdown>
<script type="text/template">
#### async / await
- RC ES7
- `async function`
- will return a Promise
- `await` keyword
- suspending execution in context
</script>
</section>
<section data-markdown>
<script type="text/template">
#### async / await
```js
const fsp = require('fs-promise');
async function(file) {
let markdown = await fsp.readFile(file);
...
}
```
Note:
- what happens
- onFulfill: assign markdown with the resolved value
- onRejection: throw an error
</script>
</section>
<section data-markdown>
<script type="text/template">
#### async / await
```js
const fsp = require('fs-promise');
async function(file) {
try {
let markdown = await fsp.readFile(file);
let somevalue = await (() => { return 42; })();
// do something
return markdown;
} catch(error) {
// handle error
// return fallbackValue;
// or
// throw error;
}
...
}
```
Note:
- await suspend executions
- try / catch like in sync context
- can return values
- Now see our Example
</script>
</section>
<section data-markdown>
<script type="text/template">
#### async / await
```js
const fsp = require('fs-promise');
const html = require('./html');
async function mdToHtml(file) {
let markdown = await fsp.readFile(file);
let htmlContent = await html.fromMarkdownProm(markdown);
await fsp.writeFile(`${file}.html`, htmlContent);
}
mdToHtml('./README.md').then(() => {
console.log('done');
}).catch((error) => {
console.error(error);
});
```
Note:
- compare to sync
</script>
</section>
<section data-markdown>
<script type="text/template">
#### Sync
```js
const fs = require('fs');
const html = require('./html');
function mdToHtml(file) {
let markdown = fs.readFileSync(file);
let htmlContent = html.fromMarkdownSync(markdown);
fs.writeFileSync(`${file}.html`, htmlContent);
}
try {
mdToHtml('./README.md');
console.log('done');
} catch(err) {
console.error(err);
}
```
Note:
- almost the same
</script>
</section>
<section data-markdown class="md-code-large">
<script type="text/template">
#### async / await
parallel execution
```js
async function () {
let promA = new Promise(...);
let promB = new Promise(...);
return await promA + await promB;
}
async function () {
let [resultA, resultB] = await Promise.all([
new Promise(...),
new Promise(...)
]);
return resultA + resultB;
}
```
</script>
</section>
<section data-markdown class="md-code-large">
<script type="text/template">
#### generator
- generator object saves it's state while suspending
```js
function* fibonacci() {
let fn1 = 1;
let fn2 = 1;
while (1){
let current = fn2;
fn2 = fn1;
fn1 = fn1 + current;
let reset = yield current;
if (reset){
fn1 = 1;
fn2 = 1;
}
}
}
let sequence = fibonacci();
console.log(sequence.next()); // { done: false, value: 1}
console.log(sequence.next().value); // 1
console.log(sequence.next().value); // 2
console.log(sequence.next(true).value); // 1
```
Note:
- generator function
- generator object
- pass arg to next
- suspend / resume
- iterable: g[Symbol.iterator] === function
- iterable: g[Symbol.iterator]: () => ({ next() { return { done: true, value: 1 }})
- iterable: @@iterator
- iterator: g.next === function
</script>
</section>
<section data-markdown class="md-code-large">
<script type="text/template">
#### generator
```js
function* generatorFunction() {
let current = '';
current = yield current;
console.log(current);
// ...
current = yield current;
console.log(current);
// ...
current = yield current;
console.log(current);
}
```
Note:
- iterable: g[Symbol.iterator] === function
- iterable: g[Symbol.iterator]: () => ({ next() { return { done: true, value: 1 }})
- iterable: @@iterator
- iterator: g.next === function
- suspend / resume, already heared
-
</script>
</section>
<section data-markdown class="md-code-large">
<script type="text/template">
#### generator
```js
function remote(genFunc) {
let generatorObject = genFunc();
getNext();
function getNext(answer) {
let message = generatorObject.next(answer);
if (message.done) { return; }
remoteLog(message.value, getNext);
},
function remoteLog(value, next) {
ajax.post('https://my-remote.com', { value })
.then((answer) => { next(answer);})
.catch((err) => { generatorObject.throw(err); });
}
}
remote(function* logMessages() {
try {
let msg = 'Message 1';
msg = yield msg;
//...
msg = yield msg;
} catch(err) { console.error(err); }
});
```
</script>
</section>
<section data-markdown class="md-code-large">
<script type="text/template">
#### generator
Using co
```js
const co = require('co');
co(function *(){
let markdown = yield fs.readFile('README.md');
let htmlContent = html.fromMarkdownSync(markdown);
...
}).catch(onerror);
```
Note:
- co
</script>
</section>
<section>
<h1>Thank you</h1>
</section>
</div>
</div>
<script src="lib/js/head.min.js"></script>
<script src="js/reveal.js"></script>
<script>
// More info https://github.com/hakimel/reveal.js#configuration
Reveal.initialize({
history: true,
transition: 'default',
progress: false,
slideNumber: true,
// More info https://github.com/hakimel/reveal.js#dependencies
dependencies: [
{ src: 'plugin/markdown/marked.js' },
{ src: 'plugin/markdown/markdown.js' },
{ src: 'plugin/notes/notes.js', async: true },
{ src: 'plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } }
]
});
</script>
</body>
</html>