-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.html
1369 lines (1270 loc) · 61.3 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
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="author" content="" />
<link rel="author" href="humans.txt" />
<meta
name="description"
content="JavaScript tutorials and web development articles including topics like NodeJS, Angular, VueJS, Data Structures and Algorithms."
/>
<meta
name="viewport"
content="width=device-width, initial-scale=1.0, minimum-scale=1.0"
/>
<link
rel="alternative"
href="/atom.xml"
title=" Blog"
type="application/atom+xml"
/>
<title>Understanding JavaScript Callbacks and best practices | Blog</title>
<!-- Favicons -->
<link
rel="apple-touch-icon-precomposed"
sizes="57x57"
href="/apple-touch-icon-57x57.png"
/>
<link
rel="apple-touch-icon-precomposed"
sizes="114x114"
href="/apple-touch-icon-114x114.png"
/>
<link
rel="apple-touch-icon-precomposed"
sizes="72x72"
href="/apple-touch-icon-72x72.png"
/>
<link
rel="apple-touch-icon-precomposed"
sizes="144x144"
href="/apple-touch-icon-144x144.png"
/>
<link
rel="apple-touch-icon-precomposed"
sizes="60x60"
href="/apple-touch-icon-60x60.png"
/>
<link
rel="apple-touch-icon-precomposed"
sizes="120x120"
href="/apple-touch-icon-120x120.png"
/>
<link
rel="apple-touch-icon-precomposed"
sizes="76x76"
href="/apple-touch-icon-76x76.png"
/>
<link
rel="apple-touch-icon-precomposed"
sizes="152x152"
href="/apple-touch-icon-152x152.png"
/>
<link
rel="icon"
type="image/png"
href="/favicon-196x196.png"
sizes="196x196"
/>
<link rel="icon" type="image/png" href="/favicon-96x96.png" sizes="96x96" />
<link rel="icon" type="image/png" href="/favicon-32x32.png" sizes="32x32" />
<link rel="icon" type="image/png" href="/favicon-16x16.png" sizes="16x16" />
<link rel="icon" type="image/png" href="/favicon-128.png" sizes="128x128" />
<meta name="application-name" content="'s Blog" />
<meta name="msapplication-TileColor" content="#FFFFFF" />
<meta name="msapplication-TileImage" content="/mstile-144x144.png" />
<meta name="msapplication-square70x70logo" content="/mstile-70x70.png" />
<meta
name="msapplication-square150x150logo"
content="/mstile-150x150.png"
/>
<meta name="msapplication-wide310x150logo" content="/mstile-310x150.png" />
<meta
name="msapplication-square310x310logo"
content="/mstile-310x310.png"
/>
<meta
name="msapplication-notification"
content="frequency=30;polling-uri=http://notifications.buildmypinnedsite.com/?feed=https://master--bgoonz-blog.netlify.app/atom.xml"
/>
<link
rel="canonical"
href="https://master--bgoonz-blog.netlify.app/callbacks-concurrency-in-javascript-node/"
/>
<!-- Open Graph -->
<meta
property="og:url"
content="https://master--bgoonz-blog.netlify.app/callbacks-concurrency-in-javascript-node/"
/>
<meta property="og:site_name" content=" Blog" />
<meta property="og:type" content="article" />
<meta
property="og:description"
content="Callbacks are one of the critical elements to understand JavaScript and Node.js. Nearly, all the asynchronous functions use a callback (or promises). In this post, we are going to cover callbacks in-depth and best practices."
/>
<meta
property="og:image"
content="https://master--bgoonz-blog.netlify.app/images/callbacks-concurrency-in-javascript-large.png"
/>
<meta
property="og:title"
content="Understanding JavaScript Callbacks and best practices"
/>
<meta property="fb:app_id" content="761831487293468" />
<meta property="fb:admins" content="895685163" />
<!-- /Open Graph -->
<!-- Critical Styles -->
<style media="screen">
.overlay {
display: none;
}
</style>
<link rel="stylesheet" href="/stylesheets/main.css" />
<!-- loadDeferredStyles -->
<noscript id="deferred-styles">
<link rel="stylesheet" href="/stylesheets/font-awesome.min.css" />
</noscript>
<script>
var loadDeferredStyles = function () {
var addStylesNode = document.getElementById("deferred-styles");
var replacement = document.createElement("div");
replacement.innerHTML = addStylesNode.textContent;
document.body.appendChild(replacement);
addStylesNode.parentElement.removeChild(addStylesNode);
};
var raf =
requestAnimationFrame ||
mozRequestAnimationFrame ||
webkitRequestAnimationFrame ||
msRequestAnimationFrame;
if (raf)
raf(function () {
window.setTimeout(loadDeferredStyles, 0);
});
else window.addEventListener("load", loadDeferredStyles);
</script>
<meta name="generator" content="Hexo 5.0.2" />
</head>
<body>
<header class="titlebar mdl-shadow--2dp">
<div class="container align-center flexbox--space-between">
<!-- <div class="row"> -->
<!-- <div class="col-md-12"> -->
<span class="hidden-mobile-up">
<i class="fa fa-bars" aria-hidden="true"></i>
</span>
<a href="/" class="align-center m-y-2">
<img
src="/images/adrianmejia-logo.png"
alt=" Logo"
class="animation--bounce-in"
/>
<h1 class="hidden-mobile-down hidden"></h1>
</a>
<nav class="hidden-mobile-down navbar">
<a
href="/#home"
class="animation--radial-out"
id="Home"
onclick="track('/#home', 'menu', true)"
>Home</a
>
<a
href="/#trending-posts"
class="animation--radial-out"
id="Trending"
onclick="track('/#trending-posts', 'menu', true)"
>Trending</a
>
<a
href="/#popular-posts"
class="animation--radial-out"
id="Popular"
onclick="track('/#popular-posts', 'menu', true)"
>Popular</a
>
<a
href="/#about"
class="animation--radial-out"
id="About"
onclick="track('/#about', 'menu', true)"
>About</a
>
<a
href="/blog/"
class="animation--radial-out"
id="Blog"
onclick="track('/blog/', 'menu', true)"
>Blog</a
>
</nav>
<a
href="#"
id="search-modal"
onclick="track('#search', 'search', true)"
class="open-overlay"
>
<i class="fa fa-search" aria-hidden="true"></i>
</a>
<div id="search-overlay" class="overlay" aria-hidden="true">
<script id="movie" type="text/x-handlebars-template">
<article class="movie">
{{#photos.0}}
<a href="/{{path}}">
<img class="movie-image" src="{{photos.0}}" />
</a>
{{/photos.0}}
<div class="movie-meta">
<div class="movie-title">
<a href="/{{path}}">
{{{_highlightResult.title.value}}}
</a>
<span class="movie-year">
{{updatedYear}}
</span>
</div>
<div class="movie-rating">
{{#stars}}
<span class="ais-star-rating--star{{^.}}__empty{{/.}}">
</span>
{{/stars}}
</div>
<p>
{{{_highlightResult.excerptStrip.value}}}
</p>
<div class="movie-genres">
{{#tags}}
<div class="movie-genre">
{{.}}
</div>
{{/tags}}
</div>
</div>
</article>
</script>
<div class="search-container">
<div class="top">
<div class="search-button">
<i class="fa fa-search"></i>
</div>
<div class="input-container">
<input type="text" id="search-box" />
<div id="stats"></div>
</div>
<a href="#" class="close-overlay">
<i class="fa fa-times"></i>
</a>
</div>
<div class="content">
<div class="facets">
<div class="facet">
<div id="clear-all" class="facet-title"></div>
</div>
<div class="facet">
<div class="facet-title">
<i class="fa fa-tags" aria-hidden="true"></i> Tags
</div>
<div id="tags"></div>
</div>
<div class="facet">
<div class="facet-title">
<i class="fa fa-folder-o" aria-hidden="true"></i>
Categories
</div>
<div id="categories"></div>
</div>
<div class="facet">
<div class="facet-title">
<i class="fa fa-eye" aria-hidden="true"></i>
Views
</div>
<div id="ratings"></div>
</div>
<div class="facet">
<div class="facet-title">
<i class="fa fa-calendar" aria-hidden="true"></i>
Year
</div>
<div id="year"></div>
</div>
</div>
<div class="canvas">
<div id="hits"></div>
<div id="pagination"></div>
<div>
Powered by
<img
src="/images/Algolia_logo_bg-white.svg"
height="30"
alt="Algolia search"
/>
</div>
</div>
</div>
</div>
</div>
<script src="/js/search.babel.js"></script>
</div>
</header>
<nav class="hidden-mobile-up mdl-shadow--2dp">
<div class="container flexbox--space-between navbar">
<a href="/#home" class="animation--underline-from-center">Home</a>
<a href="/#trending-posts" class="animation--underline-from-center"
>Trending</a
>
<a href="/#popular-posts" class="animation--underline-from-center"
>Popular</a
>
<a href="/#about" class="animation--underline-from-center">About</a>
<a href="/blog/" class="animation--underline-from-center">Blog</a>
</div>
</nav>
<main>
<!--https://developers.google.com/search/docs/data-types/articles-->
<!--http://schema.org/BlogPosting-->
<script type="application/ld+json">
{
"@context": "http://schema.org",
"@type": "BlogPosting",
"mainEntityOfPage": {
"@type": "WebPage",
"@id": ""
},
"headline": "Understanding JavaScript Callbacks and best practices",
"image": {
"@type": "ImageObject",
"url": "https://master--bgoonz-blog.netlify.app/images/callbacks-concurrency-in-javascript-large.png",
"height": 360,
"width": 728
},
"datePublished": "2019-07-03T19:06:12-04:00",
"dateModified": "2019-07-03T19:06:12-04:00",
"author": {
"@type": "Person",
"name": ""
},
"publisher": {
"@type": "Organization",
"name": "",
"logo": {
"@type": "ImageObject",
"url": "https://master--bgoonz-blog.netlify.app/images/logo.png",
"width": 347,
"height": 50
}
},
"description": "Callbacks are one of the critical elements to understand JavaScript and Node.js. Nearly, all the asynchronous functions use a callback (or promises). In this post, we are going to cover callbacks in-depth and best practices."
}
</script>
<article class="container post">
<section class="hero">
<div class="muted">
<a class="category-link" href="/categories/coding/">Coding</a>
</div>
<h1>Understanding JavaScript Callbacks and best practices</h1>
<div class="muted">
<span title="Last time this post was updated">
<i class="fa fa-calendar" aria-hidden="true"></i>
Last updated
<time datetime="2019-07-03T23:06:12.000Z" itemprop="dateUpdated"
>July 3rd 2019</time
>
</span>
<span class="m-x-2" title="Pageviews">
<i class="fa fa-eye" aria-hidden="true"></i>
6.3k
</span>
<span class="m-x-2" title="Click to go to the comments section">
<a href="#disqus_thread">
<i class="fa fa-comment-o" aria-hidden="true"></i>
<span
class="disqus-comment-count"
data-disqus-url="https://master--bgoonz-blog.netlify.app/callbacks-concurrency-in-javascript-node/"
>0</span
>
</a>
</span>
<span>
<ul class="tag-list" itemprop="keywords">
<li class="tag-list-item">
<a class="tag-list-link" href="/tags/javascript/" rel="tag"
>javascript</a
><span class="tag-list-count">5</span>
</li>
<li class="tag-list-item">
<a class="tag-list-link" href="/tags/nodejs/" rel="tag"
>nodejs</a
><span class="tag-list-count">12</span>
</li>
<li class="tag-list-item">
<a
class="tag-list-link"
href="/tags/tutorial-async-javascript/"
rel="tag"
>tutorial_async-javascript</a
><span class="tag-list-count">3</span>
</li>
</ul>
</span>
</div>
</section>
<div class="art-container" style="background-color: #fbe000">
<picture>
<source
media="(min-width: 728px)"
srcset="/images/callbacks-concurrency-in-javascript-large.png"
/>
<source
srcset="/images/callbacks-concurrency-in-javascript-small.png"
/>
<img
src="/images/callbacks-concurrency-in-javascript-large.png"
alt="Understanding JavaScript Callbacks and best practices"
/>
</picture>
</div>
<div class="row">
<section class="col-sm-8 p-x-2">
<div class="post-content toc-content">
<p>
Callbacks are one of the critical elements to understand
JavaScript and Node.js. Nearly, all the asynchronous functions
use a callback (or promises). In this post, we are going to
cover callbacks in-depth and best practices.
</p>
<a id="more"></a>
<p>
This post assumes you know the
<a
href="/asynchronous-vs-synchronous-handling-concurrency-in-javascript"
>difference between synchronous and asynchronous code</a
>.
</p>
<p>
JavaScript is an event-driven language. Instead of waiting for
things to happen, it executes while listening for events. The
way you respond to an event is using callbacks.
</p>
<hr />
<p><strong>Related Posts:</strong></p>
<ol>
<li>
<a
href="/asynchronous-vs-synchronous-handling-concurrency-in-javascript/"
>Async vs Sync in JavaScript</a
>
</li>
<li>
<a href="/callbacks-concurrency-in-javascript-node/"
>JavaScript Callbacks</a
>
(this one)
</li>
<li>
<a href="/promises-tutorial-concurrency-in-javascript-node/"
>JavaScript Promises</a
>
</li>
</ol>
<hr />
<h2 id="JavaScript-callbacks">
<a
href="#JavaScript-callbacks"
class="headerlink"
title="JavaScript callbacks"
></a
>JavaScript callbacks
</h2>
<blockquote>
<p>
A callback is a function that is passed as an argument to
another function.
</p>
</blockquote>
<p>
Callbacks are also known as
<strong>higher-order function</strong>.
</p>
<p>An example of a callback is the following:</p>
<figure class="highlight js">
<table>
<tr>
<td class="gutter">
<pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre>
</td>
<td class="code">
<pre><span class="line"><span class="keyword">const</span> compute = <span class="function">(<span class="params">n1, n2, callback</span>) =></span> callback(n1, n2);</span><br><span class="line"><span class="keyword">const</span> sum = <span class="function">(<span class="params">n1, n2</span>) =></span> n1 + n2;</span><br><span class="line"><span class="keyword">const</span> product = <span class="function">(<span class="params">n1, n2</span>) =></span> n1 * n2;</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(compute(<span class="number">5</span>, <span class="number">3</span>, sum)); <span class="comment">// ↪️ 8</span></span><br><span class="line"><span class="built_in">console</span>.log(compute(<span class="number">5</span>, <span class="number">3</span>, product)); <span class="comment">// ↪️ 15</span></span><br></pre>
</td>
</tr>
</table>
</figure>
<p>
As you can see the function <code>compute</code> takes two
numbers and a callback function. This
<code>callback</code> function can be <code>sum</code>,
<code>product</code> and any other that you develop that
operates two numbers.
</p>
<h2 id="Callback-Advantages">
<a
href="#Callback-Advantages"
class="headerlink"
title="Callback Advantages"
></a
>Callback Advantages
</h2>
<p>
Callbacks can help to make your code more maintainable if you
use them well. They will also help you to:
</p>
<ul>
<li>Keep your code DRY (Do Not Repeat Yourself)</li>
<li>
Implement better abstraction where you can have more generic
functions like <code>compute</code> that can handle all sorts
of functionalities (e.g., <code>sum</code>,
<code>product</code>)
</li>
<li>Improve code readability and maintainability.</li>
</ul>
<p>
So far, we have only seen callbacks that are executed
immediately; however, most of the callbacks in JavaScript are
tied to an event like a timer, API request or reading a file.
</p>
<h2 id="Asynchronous-callbacks">
<a
href="#Asynchronous-callbacks"
class="headerlink"
title="Asynchronous callbacks"
></a
>Asynchronous callbacks
</h2>
<blockquote>
<p>
An asynchronous callback is a function that is passed as an
argument to another function
<em
>and gets invoke zero or multiple times after certain events
happens</em
>.
</p>
</blockquote>
<p>
It’s like when your friends tell you to call them back when you
arrive at the restaurant. You coming to the restaurant is the
“event” that <em>triggers</em> the callback. Something similar
happens in the programming world. The event could be you click a
button, a file is loaded into memory, and request to a server
API, and so on.
</p>
<p>Let’s see an example with two callbacks:</p>
<figure class="highlight js">
<table>
<tr>
<td class="gutter">
<pre><span class="line">1</span><br><span class="line">2</span><br></pre>
</td>
<td class="code">
<pre><span class="line"><span class="keyword">const</span> id = <span class="built_in">setInterval</span>(<span class="function">() =></span> <span class="built_in">console</span>.log(<span class="string">'tick ⏰'</span>), <span class="number">1e3</span>);</span><br><span class="line"><span class="built_in">setTimeout</span>(<span class="function">() =></span> <span class="built_in">clearInterval</span>(id), <span class="number">5e3</span>);</span><br></pre>
</td>
</tr>
</table>
</figure>
<p>
First, you notice that we are using anonymous functions (in the
previous example, we were passing the named functions such as
<code>sum</code> and <code>product</code>). The callback passed
to <code>setInterval</code> is triggered every second, and it
prints <code>tick</code>. The second callback is called one
after 5 seconds. It cancels the interval, so it just writes
<code>tick</code> five times.
</p>
<blockquote>
<p>
Callbacks are a way to make sure a particular code doesn’t
execute until another has already finished.
</p>
</blockquote>
<p>
The <code>console.log('tick')</code> only gets executed
when a second has passed.
</p>
<p>
The functions <code>setInterval</code> and
<code>setTimeout</code> callbacks are very simple. They don’t
provide any parameters on the callback functions. But, if we are
reading from the file system or network, we can get the response
as a callback parameter.
</p>
<h2 id="Callback-Parameters">
<a
href="#Callback-Parameters"
class="headerlink"
title="Callback Parameters"
></a
>Callback Parameters
</h2>
<p>
The callback parameters allow you to get messages into your
functions when they are available. Let’s say we are going to
create a vanilla server on Node.js.
</p>
<figure class="highlight js">
<table>
<tr>
<td class="gutter">
<pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre>
</td>
<td class="code">
<pre><span class="line"><span class="keyword">const</span> http = <span class="built_in">require</span>(<span class="string">'http'</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> port = <span class="number">1777</span>;</span><br><span class="line"><span class="keyword">const</span> host = <span class="string">'127.0.0.1'</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> proxy = http.createServer(<span class="function">(<span class="params">req, res</span>) =></span> {</span><br><span class="line"> res.writeHead(<span class="number">200</span>, { <span class="string">'Content-Type'</span>: <span class="string">'text/plain'</span> });</span><br><span class="line"> res.end(<span class="string">`Hello World from Node! You used url "<span class="subst">${req.url}</span>"\r\n`</span>);</span><br><span class="line">});</span><br><span class="line"></span><br><span class="line">proxy.listen(port, host, <span class="function">() =></span> {</span><br><span class="line"> <span class="built_in">console</span>.log(<span class="string">`Server running on http://<span class="subst">${host}</span>:<span class="subst">${port}</span>`</span>);</span><br><span class="line">});</span><br></pre>
</td>
</tr>
</table>
</figure>
<p>
We have two callbacks here. The <code>http.createServer</code>‘s
callback sends the parameters (<code>req</code>)uest and
(<code>res</code>)ponse every time somebody connects to the
server.
</p>
<p>You can test this server using curl (or browser)</p>
<figure class="highlight sh">
<table>
<tr>
<td class="gutter">
<pre><span class="line">1</span><br></pre>
</td>
<td class="code">
<pre><span class="line">curl 127.0.0.1:1777/this/is/cool</span><br></pre>
</td>
</tr>
</table>
</figure>
<p>
There you have it! An HTTP server that replies to everyone that
connects to it using a callback. But, What would happen if
there’s an error? Let’s see how to handle that next.
</p>
<h2 id="Handling-errors-with-Node-js-callbacks">
<a
href="#Handling-errors-with-Node-js-callbacks"
class="headerlink"
title="Handling errors with Node.js callbacks"
></a
>Handling errors with Node.js callbacks
</h2>
<p>
Some callbacks send errors on the first parameter and then the
data (<code>callback(error, data)</code>). That’s very common in
Node.js API. Let’s say we want to see all the directories on a
given folder:
</p>
<figure class="highlight js">
<table>
<tr>
<td class="gutter">
<pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre>
</td>
<td class="code">
<pre><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">'fs'</span>);</span><br><span class="line"></span><br><span class="line">fs.readdir(<span class="string">'/Users/adrian/Code'</span>, <span class="function">(<span class="params">error, files</span>) =></span> {</span><br><span class="line"> <span class="keyword">if</span> (error) { <span class="built_in">console</span>.error(error); }</span><br><span class="line"> <span class="built_in">console</span>.log(files);</span><br><span class="line">});</span><br></pre>
</td>
</tr>
</table>
</figure>
<p>
As you notice, the first parameter will have an error message.
If you run it, you would probably have the error message (unless
you have the same name and directory).
</p>
<figure class="highlight plain">
<table>
<tr>
<td class="gutter">
<pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre>
</td>
<td class="code">
<pre><span class="line">{ [Error: ENOENT: no such file or directory, scandir '/Users/noAdrian/Code']</span><br><span class="line"> errno: -2,</span><br><span class="line"> code: 'ENOENT',</span><br><span class="line"> syscall: 'scandir',</span><br><span class="line"> path: '/Users/noAdrian/Code' }</span><br><span class="line">undefined</span><br></pre>
</td>
</tr>
</table>
</figure>
<p>
So that’s how you handle errors, you check for that parameter.
But (there’s always a but) what if I need to do multiple async
operations. The easiest way (but not the best) is to have a
callback inside a callback:
</p>
<figure class="highlight js">
<table>
<tr>
<td class="gutter">
<pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre>
</td>
<td class="code">
<pre><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">'fs'</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> dir = <span class="string">'/Users/adrian/Code'</span>;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">printFilesSize</span>(<span class="params">basePath</span>) </span>{</span><br><span class="line"> fs.readdir(basePath, <span class="function">(<span class="params">err, files</span>) =></span> {</span><br><span class="line"> <span class="keyword">if</span> (err) {</span><br><span class="line"> <span class="built_in">console</span>.log(<span class="string">`Error finding files: <span class="subst">${err}</span>`</span>);</span><br><span class="line"> } <span class="keyword">else</span> {</span><br><span class="line"> files.forEach(<span class="function">(<span class="params">filename</span>) =></span> {</span><br><span class="line"> <span class="keyword">const</span> filePath = <span class="string">`<span class="subst">${basePath}</span>/<span class="subst">${filename}</span>`</span>;</span><br><span class="line"></span><br><span class="line"> fs.lstat(filePath, <span class="function">(<span class="params">err, stat</span>) =></span> {</span><br><span class="line"> <span class="keyword">if</span> (err) { <span class="built_in">console</span>.error(err); }</span><br><span class="line"> <span class="keyword">if</span> (stat.isFile()) {</span><br><span class="line"> <span class="built_in">console</span>.log(filePath, stat.size.toLocaleString());</span><br><span class="line"> }</span><br><span class="line"> });</span><br><span class="line"> });</span><br><span class="line"> }</span><br><span class="line"> });</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line">printFilesSize(dir);</span><br></pre>
</td>
</tr>
</table>
</figure>
<p>
As you can see, this program will first read files in a
directory and then check the file size of each file, and if it’s
a directory, it will be omitted.
</p>
<p>
When callbacks are nested too many levels deep, we call this
callback hell! 🔥 Or the pyramid of doom ⚠️
</p>
<p><img src="/images/callback-hell.gif" alt="callback hell" /></p>
<p>
Because they are hard to maintain, how do we fix the callback
hell? Read on!
</p>
<h2 id="Callback-Hell-problem-and-solutions">
<a
href="#Callback-Hell-problem-and-solutions"
class="headerlink"
title="Callback Hell problem and solutions"
></a
>Callback Hell problem and solutions
</h2>
<p>Callback hell is when you have too many nested callbacks.</p>
<figure class="highlight js">
<table>
<tr>
<td class="gutter">
<pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre>
</td>
<td class="code">
<pre><span class="line">a(<span class="function">() =></span> {</span><br><span class="line"> b(<span class="function">() =></span> {</span><br><span class="line"> c(<span class="function">() =></span> {</span><br><span class="line"> d();</span><br><span class="line"> });</span><br><span class="line"> });</span><br><span class="line">});</span><br></pre>
</td>
</tr>
</table>
</figure>
<p>To make your code better, you should:</p>
<ol>
<li>
Keep you code shallow (avoid too many nested functions): keep
your code at 1-3 indentation levels.
</li>
<li>
Modularize: convert your anonymous callbacks into named
functions.
</li>
<li>Use promises and async/await.</li>
</ol>
<p>
Let’s fix the callback hell from
<code>printFilesSize</code> keeping our code shallow and
modularizing it.
</p>
<figure class="highlight js">
<table>
<tr>
<td class="gutter">
<pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre>
</td>
<td class="code">
<pre><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">'fs'</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> dir = <span class="string">'/Users/adrian/Code'</span>;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">printFileSize</span>(<span class="params">filePath</span>) </span>{</span><br><span class="line"> fs.lstat(filePath, <span class="function">(<span class="params">err, stat</span>) =></span> {</span><br><span class="line"> <span class="keyword">if</span> (err) { <span class="built_in">console</span>.error(err); }</span><br><span class="line"> <span class="keyword">if</span> (stat.isFile()) {</span><br><span class="line"> <span class="built_in">console</span>.log(filePath, stat.size.toLocaleString());</span><br><span class="line"> }</span><br><span class="line"> });</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">printFilesSize</span>(<span class="params">files, basePath</span>) </span>{</span><br><span class="line"> files.forEach(<span class="function">(<span class="params">filename</span>) =></span> {</span><br><span class="line"> <span class="keyword">const</span> filePath = <span class="string">`<span class="subst">${basePath}</span>/<span class="subst">${filename}</span>`</span>;</span><br><span class="line"></span><br><span class="line"> printFileSize(filePath);</span><br><span class="line"> });</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">printFilesSizeFromDirectory</span>(<span class="params">basePath</span>) </span>{</span><br><span class="line"> fs.readdir(basePath, <span class="function">(<span class="params">err, files</span>) =></span> {</span><br><span class="line"> <span class="keyword">if</span> (err) {</span><br><span class="line"> <span class="built_in">console</span>.log(<span class="string">`Error finding files: <span class="subst">${err}</span>`</span>);</span><br><span class="line"> } <span class="keyword">else</span> {</span><br><span class="line"> printFilesSize(files, basePath);</span><br><span class="line"> }</span><br><span class="line"> });</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line">printFilesSizeFromDirectory(dir);</span><br></pre>
</td>
</tr>
</table>
</figure>
<p>
The original implement had five levels of indentation, now that
we modularized it is 1-2 levels.
</p>
<p>
Callbacks are not the only way to deal with asynchronous code.
In the following post we are going to cover:
</p>
<ul>
<li>Promises</li>
<li>Async/Await</li>
<li>Generators</li>
</ul>
<p>Stay tuned!</p>
<hr />
<p><strong>Related Posts:</strong></p>
<ol>
<li>
<a
href="/asynchronous-vs-synchronous-handling-concurrency-in-javascript/"
>Async vs Sync in JavaScript</a
>
</li>
<li>
<a href="/callbacks-concurrency-in-javascript-node/"
>JavaScript Callbacks</a
>
(this one)
</li>
<li>
<a href="/promises-tutorial-concurrency-in-javascript-node/"
>JavaScript Promises</a
>
</li>
</ol>
<hr />
</div>
<!-- after post -->
<div class="hidden-mobile-down">
<h3>Now, your turn!</h3>
Thanks for reading this far. Here are some things you can do next:
<ul>
<li>
Found a typo?
<a
target="_blank"
rel="noopener"
href="https://github.com/amejiarosario/amejiarosario.github.io/edit/source/source/_posts/2019-07-03-callbacks-concurrency-in-javascript-node.md"
>
Edit this post</a
>.
</li>
<li>
Got questions?
<a href="#comments-section">comment</a>
below.
</li>
<li>
Was it useful? Show your
<!-- <a href="/support">support</a> -->
support and share it.
<!-- <a target="_blank" href="http://paypal.me/amejiarosario">Paypal</a>, -->
<!-- <a target="_blank" href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=HZLFWQAFENN7W&source=url">Paypal</a>,
<a target="_blank" href="https://bitaps.com/3A8xanut3wddz1jJ7JWSw8nwwpUahLJpZi">Bitcoin</a>,
<a target="_blank" href="https://www.patreon.com/amejiarosario">Patreon</a>. -->
</li>
</ul>
</div>
<div class="hidden-mobile-up">
<a
target="_blank"
rel="noopener"
href="https://books.adrianmejia.com"
>
<!-- <img src="/images/data-structure-algorithms-javascript-presell.jpg" alt="Data Structure and Algorithms in JavaScript eBook"> -->
<img
src="/images/data-structure-algorithms-banner.jpg"
alt="Data Structure and Algorithms in JavaScript eBook"
/>
</a>
</div>
<!-- Next and previous posts -->
<div class="article-nav m-y-4">
<a
href="/promises-tutorial-concurrency-in-javascript-node/"
class="article-nav-newer"
class="article-nav-link-wrap"
>
<strong class="article-nav-caption"
><i class="fa fa-chevron-left"></i> newer</strong
>
<div class="article-nav-title">
The JavaScript Promise Tutorial
</div>
</a>
<a
href="/asynchronous-vs-synchronous-handling-concurrency-in-javascript/"
class="article-nav-older"
class="article-nav-link-wrap"
>
<strong class="article-nav-caption"
>older <i class="fa fa-chevron-right"></i
></strong>
<div class="article-nav-title">
What every programmer should know about Synchronous vs.
Asynchronous Code
</div>
</a>
</div>
<!-- Related -->
<footer>
<!-- subscribe -->
<div class="m-y-4">
<!-- Begin MailChimp Signup Form -->
<link
href="//cdn-images.mailchimp.com/embedcode/horizontal-slim-10_7.css"
rel="stylesheet"
type="text/css"
/>
<style type="text/css">
#mc_embed_signup {
background: #fff;
clear: left;
font: 14px Helvetica, Arial, sans-serif;
width: 100%;
}
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
</style>
<div id="mc_embed_signup">
<form
action="//adrianmejia.us2.list-manage.com/subscribe/post?u=2294bb28c5931a6f2338d2474&id=52678e825b"
method="post"
id="mc-embedded-subscribe-form"
name="mc-embedded-subscribe-form"
class="validate"
novalidate
>
<div id="mc_embed_signup_scroll">
<label for="mce-EMAIL"
>Subscribe & stay up to date!</label
>
<input
type="email"
value=""
name="EMAIL"
class="email"
id="mce-EMAIL"
placeholder="email address"
required
/>
<!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
<div
style="position: absolute; left: -5000px"
aria-hidden="true"
>
<input
type="text"
name="b_2294bb28c5931a6f2338d2474_52678e825b"