-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathjavascript.html
More file actions
1422 lines (1175 loc) · 83 KB
/
javascript.html
File metadata and controls
1422 lines (1175 loc) · 83 KB
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">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Deep Dive - Better Dev</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<header class="topbar">
<button class="sidebar-toggle" aria-label="Open navigation" aria-expanded="false">
<span class="hamburger-icon"></span>
</button>
<a href="index.html" class="logo">Better Dev</a>
</header>
<div class="sidebar-backdrop" aria-hidden="true"></div>
<aside class="sidebar" aria-label="Site navigation">
<div class="sidebar-header">
<span class="sidebar-title">Navigation</span>
<button class="sidebar-close" aria-label="Close navigation">×</button>
</div>
<div class="sidebar-search">
<input type="text" class="sidebar-search-input" placeholder="Search topics..." aria-label="Search topics">
<div class="sidebar-search-results"></div>
</div>
<nav class="sidebar-nav">
<div class="sidebar-group">
<a href="index.html">Home</a>
</div>
<div class="sidebar-group">
<div class="sidebar-group-label">Mathematics</div>
<a href="pre-algebra.html">Pre-Algebra</a>
<a href="algebra.html">Algebra</a>
<a href="sequences-series.html">Sequences & Series</a>
<a href="geometry.html">Geometry</a>
<a href="calculus.html">Calculus</a>
<a href="discrete-math.html">Discrete Math</a>
<a href="linear-algebra.html">Linear Algebra</a>
<a href="probability.html">Probability & Statistics</a>
<a href="binary-systems.html">Binary & Number Systems</a>
<a href="number-theory.html">Number Theory for CP</a>
<a href="computational-geometry.html">Computational Geometry</a>
<a href="game-theory.html">Game Theory</a>
</div>
<div class="sidebar-group">
<div class="sidebar-group-label">Data Structures & Algorithms</div>
<a href="dsa-foundations.html">DSA Foundations</a>
<a href="arrays.html">Arrays & Strings</a>
<a href="stacks-queues.html">Stacks & Queues</a>
<a href="hashmaps.html">Hash Maps & Sets</a>
<a href="linked-lists.html">Linked Lists</a>
<a href="trees.html">Trees & BST</a>
<a href="graphs.html">Graphs</a>
<a href="sorting.html">Sorting & Searching</a>
<a href="patterns.html">LeetCode Patterns</a>
<a href="dp.html">Dynamic Programming</a>
<a href="advanced.html">Advanced Topics</a>
<a href="string-algorithms.html">String Algorithms</a>
<a href="advanced-graphs.html">Advanced Graphs</a>
<a href="advanced-dp.html">Advanced DP</a>
<a href="advanced-ds.html">Advanced Data Structures</a>
<a href="leetcode-650.html">The 650 Problems</a>
<a href="competitive-programming.html">CP Roadmap</a>
</div>
<div class="sidebar-group">
<div class="sidebar-group-label">Languages & Systems</div>
<a href="cpp.html">C++</a>
<a href="golang.html">Go</a>
<a href="javascript.html">JavaScript Deep Dive</a>
<a href="typescript.html">TypeScript</a>
<a href="nodejs.html">Node.js Internals</a>
<a href="os.html">Operating Systems</a>
<a href="linux.html">Linux</a>
<a href="git.html">Git</a>
<a href="backend.html">Backend</a>
<a href="system-design.html">System Design</a>
<a href="networking.html">Networking</a>
<a href="cloud.html">Cloud & Infrastructure</a>
<a href="docker.html">Docker & Compose</a>
<a href="kubernetes.html">Kubernetes</a>
<a href="message-queues.html">Queues & Pub/Sub</a>
<a href="selfhosting.html">VPS & Self-Hosting</a>
<a href="databases.html">PostgreSQL & MySQL</a>
<a href="stripe.html">Stripe & Payments</a>
<a href="distributed-systems.html">Distributed Systems</a>
<a href="backend-engineering.html">Backend Engineering</a>
</div>
<div class="sidebar-group">
<div class="sidebar-group-label">JS/TS Ecosystem</div>
<a href="js-tooling.html">Tooling & Bundlers</a>
<a href="js-testing.html">Testing</a>
<a href="ts-projects.html">Building with TS</a>
</div>
<div class="sidebar-group">
<div class="sidebar-group-label">More</div>
<a href="seans-brain.html">Sean's Brain</a>
</div>
</nav>
</aside>
<div class="container">
<div class="page-header">
<div class="breadcrumb"><a href="index.html">Home</a> / JavaScript Deep Dive</div>
<h1>JavaScript -- The Complete Deep Dive</h1>
<p>Understand JavaScript from the engine level up: how V8 compiles your code, what the event loop actually does, how closures and prototypes work under the hood, and every ES6+ feature explained so it clicks. This is the page that turns "I know JS" into "I <em>understand</em> JS."</p>
</div>
<div class="toc">
<h4>Table of Contents</h4>
<a href="#how-js-works">1. How JavaScript Actually Works</a>
<a href="#execution-context">2. Execution Context & Hoisting</a>
<a href="#scope-closures">3. Scope & Closures</a>
<a href="#this-keyword">4. The <code>this</code> Keyword</a>
<a href="#prototypes">5. Prototypes & Inheritance</a>
<a href="#event-loop">6. The Event Loop</a>
<a href="#promises">7. Promises & Async/Await</a>
<a href="#concurrency-control">8. Async Patterns -- p-limit, Resource Pools & Concurrency Control</a>
<a href="#es6-features">9. ES6+ Features (Harmony)</a>
<a href="#proxy-reflect">10. Proxy & Reflect</a>
<a href="#modules">11. Modules (CJS vs ESM)</a>
<a href="#memory">12. Memory Management</a>
<a href="#gotchas">13. Weird Parts & Gotchas</a>
</div>
<!-- ============================================================ -->
<section id="how-js-works">
<h2>1. How JavaScript Actually Works</h2>
<p>JavaScript is a <strong>single-threaded, dynamically typed, garbage-collected</strong> language. But saying that doesn't explain what's really happening. Let's go deeper.</p>
<h3>The V8 Engine (Chrome & Node)</h3>
<p>V8 is the engine that powers Chrome and Node.js. It takes your JavaScript source code and turns it into machine code that your CPU can execute. Here's the pipeline:</p>
<div class="example-box">
<div class="label">V8 Compilation Pipeline</div>
<pre><code>Source Code (.js)
|
v
Parser --> AST (Abstract Syntax Tree)
|
v
Ignition (Interpreter) --> Bytecode
|
v (if a function is called many times -- "hot")
TurboFan (JIT Compiler) --> Optimized Machine Code
|
v (if assumptions break -- "deoptimization")
Back to Ignition bytecode</code></pre>
</div>
<p><strong>JIT compilation</strong> means V8 doesn't compile everything upfront. It starts by interpreting your code into bytecode (fast startup), then identifies "hot" functions that run many times and compiles them into highly optimized machine code. If the optimized code breaks assumptions (like a variable changing types), V8 deoptimizes back to bytecode.</p>
<h3>Hidden Classes & Inline Caching</h3>
<p>V8 creates <strong>hidden classes</strong> for your objects. When you always create objects with the same shape (same properties in the same order), V8 can optimize property access to a simple memory offset lookup instead of a dictionary lookup.</p>
<pre><code><span class="lang-label">JavaScript</span>
<span class="comment">// GOOD: same shape every time -- V8 creates one hidden class</span>
<span class="keyword">function</span> <span class="function">createUser</span>(name, age) {
<span class="keyword">return</span> { name, age };
}
<span class="comment">// BAD: adding properties after creation changes the hidden class</span>
<span class="keyword">const</span> user = {};
user.name = <span class="string">"Sean"</span>; <span class="comment">// hidden class changes</span>
user.age = <span class="number">25</span>; <span class="comment">// hidden class changes again</span>
</code></pre>
<h3>The Call Stack & Heap</h3>
<p>JavaScript has two memory areas:</p>
<ul>
<li><strong>Call Stack:</strong> Where function execution contexts live. It's LIFO (last in, first out). When you call a function, a frame is pushed. When it returns, it's popped.</li>
<li><strong>Heap:</strong> Where objects, arrays, and functions are allocated. This is unstructured memory managed by the garbage collector.</li>
</ul>
<div class="warning-box">
<div class="label">Stack Overflow</div>
<p>If you call functions recursively without a base case, you'll fill up the call stack and get <code>RangeError: Maximum call stack size exceeded</code>. The default stack size is around 10,000-15,000 frames depending on the engine.</p>
</div>
<h3>Garbage Collection</h3>
<p>V8 uses a <strong>generational garbage collector</strong>:</p>
<ul>
<li><strong>Young Generation (Scavenge):</strong> Short-lived objects. Small memory area, collected frequently using a semi-space copying algorithm.</li>
<li><strong>Old Generation (Mark-Sweep-Compact):</strong> Objects that survived multiple young generation collections. Larger space, collected less often.</li>
</ul>
<p>Objects start in the young generation. If they survive two GC cycles, they're promoted to old generation. This is why short-lived objects (function-scoped variables) are cheap -- they get cleaned up quickly.</p>
</section>
<!-- ============================================================ -->
<section id="execution-context">
<h2>2. Execution Context & Hoisting</h2>
<p>When JavaScript runs your code, it creates an <strong>execution context</strong>. There are two phases:</p>
<h3>Phase 1: Creation Phase</h3>
<ul>
<li>Creates the <code>this</code> binding</li>
<li>Sets up the scope chain</li>
<li><strong>Hoists</strong> variable and function declarations</li>
</ul>
<h3>Phase 2: Execution Phase</h3>
<ul>
<li>Assigns values to variables</li>
<li>Executes code line by line</li>
</ul>
<h3>Hoisting Explained</h3>
<p>Hoisting means declarations are moved to the top of their scope during the creation phase. But <code>var</code>, <code>let</code>, <code>const</code>, and functions behave differently:</p>
<pre><code><span class="lang-label">JavaScript</span>
<span class="comment">// var is hoisted AND initialized to undefined</span>
console.<span class="function">log</span>(x); <span class="comment">// undefined (not an error!)</span>
<span class="keyword">var</span> x = <span class="number">5</span>;
<span class="comment">// let/const are hoisted but NOT initialized (Temporal Dead Zone)</span>
console.<span class="function">log</span>(y); <span class="comment">// ReferenceError: Cannot access 'y' before initialization</span>
<span class="keyword">let</span> y = <span class="number">5</span>;
<span class="comment">// Function declarations are fully hoisted (name + body)</span>
<span class="function">greet</span>(); <span class="comment">// "Hello!" -- works!</span>
<span class="keyword">function</span> <span class="function">greet</span>() { console.<span class="function">log</span>(<span class="string">"Hello!"</span>); }
<span class="comment">// Function expressions are NOT hoisted (only the variable is)</span>
<span class="function">sayBye</span>(); <span class="comment">// TypeError: sayBye is not a function</span>
<span class="keyword">var</span> sayBye = <span class="keyword">function</span>() { console.<span class="function">log</span>(<span class="string">"Bye!"</span>); };
</code></pre>
<div class="tip-box">
<div class="label">Temporal Dead Zone (TDZ)</div>
<p>The TDZ is the time between entering a scope and the <code>let</code>/<code>const</code> declaration being reached. During this time, the variable exists but you can't access it. This is why <code>let</code>/<code>const</code> are safer than <code>var</code> -- they catch bugs where you use a variable before declaring it.</p>
</div>
</section>
<!-- ============================================================ -->
<section id="scope-closures">
<h2>3. Scope & Closures</h2>
<h3>Types of Scope</h3>
<ul>
<li><strong>Global scope:</strong> Variables declared outside any function/block</li>
<li><strong>Function scope:</strong> Variables declared with <code>var</code> inside a function</li>
<li><strong>Block scope:</strong> Variables declared with <code>let</code>/<code>const</code> inside <code>{}</code></li>
</ul>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">var</span> global = <span class="string">"I'm everywhere"</span>;
<span class="keyword">function</span> <span class="function">outer</span>() {
<span class="keyword">var</span> funcScoped = <span class="string">"Only in outer()"</span>;
<span class="keyword">if</span> (<span class="keyword">true</span>) {
<span class="keyword">var</span> stillFuncScoped = <span class="string">"var ignores blocks!"</span>;
<span class="keyword">let</span> blockScoped = <span class="string">"Only in this if-block"</span>;
}
console.<span class="function">log</span>(stillFuncScoped); <span class="comment">// works! var is function-scoped</span>
console.<span class="function">log</span>(blockScoped); <span class="comment">// ReferenceError! let is block-scoped</span>
}
</code></pre>
<h3>Lexical Scope</h3>
<p>JavaScript uses <strong>lexical scoping</strong> (also called static scoping). This means a function's scope is determined by <em>where it's defined</em>, not where it's called.</p>
<h3>Closures</h3>
<p>A closure is when a function "remembers" the variables from the scope where it was created, even after that scope has finished executing. This is the single most important concept in JavaScript.</p>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">function</span> <span class="function">createCounter</span>() {
<span class="keyword">let</span> count = <span class="number">0</span>; <span class="comment">// this variable is "closed over"</span>
<span class="keyword">return</span> {
increment: () => ++count,
getCount: () => count,
};
}
<span class="keyword">const</span> counter = <span class="function">createCounter</span>();
counter.<span class="function">increment</span>();
counter.<span class="function">increment</span>();
console.<span class="function">log</span>(counter.<span class="function">getCount</span>()); <span class="comment">// 2</span>
<span class="comment">// count is not accessible directly -- it's private!</span>
</code></pre>
<h3>Classic Closure Gotcha: Loops</h3>
<pre><code><span class="lang-label">JavaScript</span>
<span class="comment">// BUG: all callbacks print 3</span>
<span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i < <span class="number">3</span>; i++) {
<span class="function">setTimeout</span>(() => console.<span class="function">log</span>(i), <span class="number">100</span>);
}
<span class="comment">// Output: 3, 3, 3 (var is function-scoped, all closures share the same i)</span>
<span class="comment">// FIX: use let (block-scoped, creates new binding each iteration)</span>
<span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i < <span class="number">3</span>; i++) {
<span class="function">setTimeout</span>(() => console.<span class="function">log</span>(i), <span class="number">100</span>);
}
<span class="comment">// Output: 0, 1, 2</span>
</code></pre>
<div class="tip-box">
<div class="label">Why Closures Matter</div>
<p>Closures enable data privacy, factory functions, callbacks, currying, memoization, and the module pattern. Every time you pass a callback to <code>.map()</code>, <code>.filter()</code>, or <code>addEventListener()</code>, you're using closures.</p>
</div>
</section>
<!-- ============================================================ -->
<section id="this-keyword">
<h2>4. The <code>this</code> Keyword</h2>
<p><code>this</code> in JavaScript is determined by <strong>how a function is called</strong>, not where it's defined. This is the opposite of how closures work (lexical), which is why it confuses people.</p>
<h3>The Rules (in order of precedence)</h3>
<table>
<tr><th>Rule</th><th>Context</th><th><code>this</code> value</th></tr>
<tr><td>1. <code>new</code></td><td><code>new Foo()</code></td><td>The newly created object</td></tr>
<tr><td>2. Explicit</td><td><code>fn.call(obj)</code>, <code>fn.apply(obj)</code>, <code>fn.bind(obj)</code></td><td><code>obj</code></td></tr>
<tr><td>3. Implicit</td><td><code>obj.fn()</code></td><td><code>obj</code></td></tr>
<tr><td>4. Default</td><td><code>fn()</code></td><td><code>globalThis</code> (or <code>undefined</code> in strict mode)</td></tr>
</table>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">const</span> user = {
name: <span class="string">"Sean"</span>,
greet() {
console.<span class="function">log</span>(<span class="string">`Hi, I'm ${<span class="keyword">this</span>.name}`</span>);
}
};
user.<span class="function">greet</span>(); <span class="comment">// "Hi, I'm Sean" (implicit: this = user)</span>
<span class="keyword">const</span> fn = user.greet;
<span class="function">fn</span>(); <span class="comment">// "Hi, I'm undefined" (default: this = globalThis)</span>
fn.<span class="function">call</span>({ name: <span class="string">"Bob"</span> }); <span class="comment">// "Hi, I'm Bob" (explicit)</span>
</code></pre>
<h3>Arrow Functions: Lexical <code>this</code></h3>
<p>Arrow functions do NOT have their own <code>this</code>. They inherit <code>this</code> from the enclosing scope (lexical binding). This is why arrow functions are perfect for callbacks but bad for object methods:</p>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">const</span> timer = {
seconds: <span class="number">0</span>,
start() {
<span class="comment">// Arrow function inherits `this` from start()</span>
<span class="function">setInterval</span>(() => {
<span class="keyword">this</span>.seconds++;
console.<span class="function">log</span>(<span class="keyword">this</span>.seconds);
}, <span class="number">1000</span>);
}
};
timer.<span class="function">start</span>(); <span class="comment">// 1, 2, 3... (this = timer, works!)</span>
<span class="comment">// If we used a regular function instead:</span>
<span class="comment">// setInterval(function() { this.seconds++; }, 1000);</span>
<span class="comment">// this would be globalThis, not timer -- BUG</span>
</code></pre>
</section>
<!-- ============================================================ -->
<section id="prototypes">
<h2>5. Prototypes & Inheritance</h2>
<p>JavaScript doesn't have classical inheritance (like Java/C++). It uses <strong>prototypal inheritance</strong>. Every object has an internal <code>[[Prototype]]</code> link to another object.</p>
<h3>The Prototype Chain</h3>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">const</span> animal = { eats: <span class="keyword">true</span> };
<span class="keyword">const</span> dog = Object.<span class="function">create</span>(animal); <span class="comment">// dog's prototype is animal</span>
dog.barks = <span class="keyword">true</span>;
console.<span class="function">log</span>(dog.barks); <span class="comment">// true (own property)</span>
console.<span class="function">log</span>(dog.eats); <span class="comment">// true (found on prototype)</span>
<span class="comment">// The chain: dog -> animal -> Object.prototype -> null</span>
</code></pre>
<h3><code>__proto__</code> vs <code>.prototype</code></h3>
<ul>
<li><code>__proto__</code> is the actual prototype link on every object (use <code>Object.getPrototypeOf()</code> instead)</li>
<li><code>.prototype</code> is a property on <strong>constructor functions</strong> that becomes the <code>__proto__</code> of instances created with <code>new</code></li>
</ul>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">function</span> <span class="function">Dog</span>(name) {
<span class="keyword">this</span>.name = name;
}
Dog.prototype.bark = <span class="keyword">function</span>() {
console.<span class="function">log</span>(<span class="string">`${<span class="keyword">this</span>.name} says woof!`</span>);
};
<span class="keyword">const</span> rex = <span class="keyword">new</span> <span class="function">Dog</span>(<span class="string">"Rex"</span>);
rex.<span class="function">bark</span>(); <span class="comment">// "Rex says woof!"</span>
<span class="comment">// rex.__proto__ === Dog.prototype --> true</span>
<span class="comment">// Dog.prototype.__proto__ === Object.prototype --> true</span>
</code></pre>
<h3>Classes Are Just Sugar</h3>
<p>ES6 <code>class</code> syntax is syntactic sugar over prototypes. It doesn't change the underlying model:</p>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">class</span> Animal {
<span class="function">constructor</span>(name) {
<span class="keyword">this</span>.name = name;
}
<span class="function">speak</span>() {
console.<span class="function">log</span>(<span class="string">`${<span class="keyword">this</span>.name} makes a noise`</span>);
}
}
<span class="keyword">class</span> Dog <span class="keyword">extends</span> Animal {
<span class="function">bark</span>() {
console.<span class="function">log</span>(<span class="string">`${<span class="keyword">this</span>.name} barks`</span>);
}
}
<span class="keyword">const</span> d = <span class="keyword">new</span> <span class="function">Dog</span>(<span class="string">"Rex"</span>);
d.<span class="function">bark</span>(); <span class="comment">// "Rex barks"</span>
d.<span class="function">speak</span>(); <span class="comment">// "Rex makes a noise" (inherited)</span>
</code></pre>
</section>
<!-- ============================================================ -->
<section id="event-loop">
<h2>6. The Event Loop</h2>
<p>This is the most important concept for understanding how JavaScript handles asynchronous code. JavaScript is single-threaded, but it can handle concurrent operations through the event loop.</p>
<div class="example-box">
<div class="label">The Event Loop Architecture</div>
<pre><code> +-----------------+
| Call Stack | (executes JS, one frame at a time)
+-----------------+
|
v
+------------------------+
| Event Loop | (checks: is stack empty?)
+------------------------+
/ | \
v v v
+----------+ +-----------+ +-----------+
| Microtask | | Macrotask | | Web APIs |
| Queue | | Queue | | (timers, |
| (Promise | |(setTimeout| | fetch, |
| .then, | | setInterval| | DOM) |
| queueMicro| | I/O, etc.)| +-----------+
+-----------+ +-----------+</code></pre>
</div>
<h3>The Loop in Action</h3>
<ol>
<li>Execute everything in the <strong>call stack</strong> until it's empty</li>
<li>Drain the <strong>microtask queue</strong> (Promise callbacks, queueMicrotask)</li>
<li>Take ONE task from the <strong>macrotask queue</strong> (setTimeout, setInterval, I/O)</li>
<li>Go back to step 2</li>
</ol>
<div class="warning-box">
<div class="label">Microtasks Always Run Before Macrotasks</div>
<p>This is the key insight. After the call stack empties, ALL microtasks run before the next macrotask. This is why <code>Promise.resolve().then()</code> always runs before <code>setTimeout(fn, 0)</code>.</p>
</div>
<pre><code><span class="lang-label">JavaScript</span>
console.<span class="function">log</span>(<span class="string">"1"</span>);
<span class="function">setTimeout</span>(() => console.<span class="function">log</span>(<span class="string">"2"</span>), <span class="number">0</span>);
Promise.<span class="function">resolve</span>().<span class="function">then</span>(() => console.<span class="function">log</span>(<span class="string">"3"</span>));
console.<span class="function">log</span>(<span class="string">"4"</span>);
<span class="comment">// Output: 1, 4, 3, 2</span>
<span class="comment">// 1: synchronous (call stack)</span>
<span class="comment">// 4: synchronous (call stack)</span>
<span class="comment">// 3: microtask (Promise.then)</span>
<span class="comment">// 2: macrotask (setTimeout)</span>
</code></pre>
<h3><code>setTimeout(fn, 0)</code> Explained</h3>
<p>It doesn't mean "run immediately." It means "run as soon as the call stack is empty AND all microtasks have been processed AND there's no other macrotask ahead of you." The minimum delay is actually ~4ms in browsers due to spec requirements.</p>
</section>
<!-- ============================================================ -->
<section id="promises">
<h2>7. Promises & Async/Await</h2>
<h3>Promise States</h3>
<p>A Promise is an object representing the eventual completion or failure of an async operation. It has three states:</p>
<ul>
<li><strong>Pending:</strong> Initial state, neither fulfilled nor rejected</li>
<li><strong>Fulfilled:</strong> Operation completed successfully</li>
<li><strong>Rejected:</strong> Operation failed</li>
</ul>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">const</span> promise = <span class="keyword">new</span> <span class="function">Promise</span>((resolve, reject) => {
<span class="comment">// async operation</span>
<span class="keyword">const</span> success = <span class="keyword">true</span>;
<span class="keyword">if</span> (success) <span class="function">resolve</span>(<span class="string">"Data!"</span>);
<span class="keyword">else</span> <span class="function">reject</span>(<span class="keyword">new</span> <span class="function">Error</span>(<span class="string">"Failed"</span>));
});
promise
.<span class="function">then</span>(data => console.<span class="function">log</span>(data)) <span class="comment">// "Data!"</span>
.<span class="function">catch</span>(err => console.<span class="function">log</span>(err)) <span class="comment">// handles rejection</span>
.<span class="function">finally</span>(() => console.<span class="function">log</span>(<span class="string">"done"</span>)); <span class="comment">// always runs</span>
</code></pre>
<h3>Promise Internals -- How It Actually Works</h3>
<p>When you write <code>new Promise(executor)</code>, the engine does several things that are worth understanding deeply. The Promise spec (Promises/A+) is surprisingly small, but its implications are huge.</p>
<p><strong>The executor runs synchronously.</strong> This is the most common misconception. The function you pass to <code>new Promise()</code> runs immediately, on the current call stack. It is NOT deferred:</p>
<pre><code><span class="lang-label">JavaScript</span>
console.<span class="function">log</span>(<span class="string">"before"</span>);
<span class="keyword">const</span> p = <span class="keyword">new</span> <span class="function">Promise</span>((resolve) => {
console.<span class="function">log</span>(<span class="string">"executor runs NOW"</span>); <span class="comment">// synchronous!</span>
<span class="function">resolve</span>(<span class="string">"done"</span>);
console.<span class="function">log</span>(<span class="string">"after resolve -- still runs"</span>); <span class="comment">// resolve doesn't return/throw</span>
});
console.<span class="function">log</span>(<span class="string">"after constructor"</span>);
p.<span class="function">then</span>(v => console.<span class="function">log</span>(<span class="string">"then:"</span>, v));
console.<span class="function">log</span>(<span class="string">"end"</span>);
<span class="comment">// Output:</span>
<span class="comment">// "before"</span>
<span class="comment">// "executor runs NOW"</span>
<span class="comment">// "after resolve -- still runs"</span>
<span class="comment">// "after constructor"</span>
<span class="comment">// "end"</span>
<span class="comment">// "then: done" <-- microtask, runs after all sync code</span>
</code></pre>
<p><strong><code>.then()</code> registers microtasks.</strong> When you call <code>.then()</code>, the callback is not invoked immediately even if the Promise is already resolved. Instead, it is scheduled as a microtask. This guarantees consistent asynchronous behavior -- you can always rely on <code>.then()</code> callbacks running after the current synchronous code finishes.</p>
<p><strong>The Promise Resolution Procedure (thenable detection).</strong> When you resolve a Promise with a value, the engine checks: is this value a "thenable" (an object with a <code>.then</code> method)? If so, it recursively unwraps it. This is why you can resolve a Promise with another Promise and it "flattens" automatically:</p>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">const</span> inner = <span class="keyword">new</span> <span class="function">Promise</span>(r => <span class="function">setTimeout</span>(() => <span class="function">r</span>(<span class="string">"inner value"</span>), <span class="number">1000</span>));
<span class="keyword">const</span> outer = <span class="keyword">new</span> <span class="function">Promise</span>(resolve => {
<span class="function">resolve</span>(inner); <span class="comment">// resolve with a Promise -- it unwraps!</span>
});
outer.<span class="function">then</span>(v => console.<span class="function">log</span>(v)); <span class="comment">// "inner value" (after 1s, not a Promise object)</span>
<span class="comment">// This also works with any "thenable" (duck typing):</span>
<span class="keyword">const</span> fakeThenable = {
<span class="function">then</span>(onFulfill) {
<span class="function">onFulfill</span>(<span class="string">"I'm not a real Promise but I quack like one"</span>);
}
};
Promise.<span class="function">resolve</span>(fakeThenable).<span class="function">then</span>(console.log);
<span class="comment">// "I'm not a real Promise but I quack like one"</span>
</code></pre>
<p><strong>Why you cannot cancel a Promise.</strong> A Promise represents a value that will exist in the future. Once created, there is no built-in mechanism to cancel it. The executor has already started running. The best you can do is ignore the result (using an <code>AbortController</code> pattern or a cancellation token), but the underlying work (network request, timer, etc.) may still complete. This is a deliberate design choice -- Promises are about the <em>result</em>, not the <em>operation</em>.</p>
<p><strong><code>Promise.withResolvers()</code> (ES2024).</strong> A newer addition that gives you the resolve/reject functions without nesting inside the executor. This is extremely useful when the resolution happens in a completely different context:</p>
<pre><code><span class="lang-label">JavaScript</span>
<span class="comment">// Old pattern: awkward variable hoisting</span>
<span class="keyword">let</span> resolve, reject;
<span class="keyword">const</span> promise = <span class="keyword">new</span> <span class="function">Promise</span>((res, rej) => {
resolve = res;
reject = rej;
});
<span class="comment">// New pattern: Promise.withResolvers()</span>
<span class="keyword">const</span> { promise: p, resolve: res, reject: rej } = Promise.<span class="function">withResolvers</span>();
<span class="comment">// Now you can resolve/reject from anywhere:</span>
<span class="function">setTimeout</span>(() => <span class="function">res</span>(<span class="string">"resolved from a timer!"</span>), <span class="number">1000</span>);
<span class="comment">// Real use case: wrapping event emitters</span>
<span class="keyword">function</span> <span class="function">waitForEvent</span>(emitter, eventName) {
<span class="keyword">const</span> { promise, resolve } = Promise.<span class="function">withResolvers</span>();
emitter.<span class="function">once</span>(eventName, resolve);
<span class="keyword">return</span> promise;
}
</code></pre>
<h3>Promise Combinators</h3>
<table>
<tr><th>Method</th><th>Resolves when</th><th>Rejects when</th></tr>
<tr><td><code>Promise.all()</code></td><td>ALL promises resolve</td><td>ANY promise rejects</td></tr>
<tr><td><code>Promise.allSettled()</code></td><td>ALL promises settle (resolve or reject)</td><td>Never rejects</td></tr>
<tr><td><code>Promise.race()</code></td><td>FIRST promise settles</td><td>FIRST promise rejects</td></tr>
<tr><td><code>Promise.any()</code></td><td>FIRST promise resolves</td><td>ALL promises reject</td></tr>
</table>
<h3>Async/Await -- What the Engine Actually Does</h3>
<p><code>async/await</code> is syntactic sugar over Promises, but understanding the transformation the engine performs helps you reason about execution order and avoid bugs.</p>
<p><strong>An <code>async</code> function always returns a Promise.</strong> Even if you return a plain value, it gets wrapped in <code>Promise.resolve()</code>. If you throw, the returned Promise is rejected:</p>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">async function</span> <span class="function">getNumber</span>() {
<span class="keyword">return</span> <span class="number">42</span>;
}
<span class="comment">// Equivalent to:</span>
<span class="keyword">function</span> <span class="function">getNumber</span>() {
<span class="keyword">return</span> Promise.<span class="function">resolve</span>(<span class="number">42</span>);
}
<span class="keyword">async function</span> <span class="function">throwError</span>() {
<span class="keyword">throw</span> <span class="keyword">new</span> <span class="function">Error</span>(<span class="string">"oops"</span>);
}
<span class="comment">// Equivalent to:</span>
<span class="keyword">function</span> <span class="function">throwError</span>() {
<span class="keyword">return</span> Promise.<span class="function">reject</span>(<span class="keyword">new</span> <span class="function">Error</span>(<span class="string">"oops"</span>));
}
</code></pre>
<p><strong><code>await</code> suspends the function and adds a continuation to the microtask queue.</strong> When the engine hits <code>await</code>, it pauses the async function, returns control to the caller, and schedules the rest of the function as a microtask that runs when the awaited Promise settles. The call stack is free to do other work in the meantime:</p>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">async function</span> <span class="function">demo</span>() {
console.<span class="function">log</span>(<span class="string">"A"</span>);
<span class="keyword">await</span> Promise.<span class="function">resolve</span>();
console.<span class="function">log</span>(<span class="string">"B"</span>); <span class="comment">// this is a microtask continuation</span>
}
console.<span class="function">log</span>(<span class="string">"1"</span>);
<span class="function">demo</span>();
console.<span class="function">log</span>(<span class="string">"2"</span>);
<span class="comment">// Output: "1", "A", "2", "B"</span>
<span class="comment">// "A" runs synchronously (before the first await)</span>
<span class="comment">// "2" runs because demo() returned control at the await</span>
<span class="comment">// "B" runs as a microtask after the synchronous code finishes</span>
</code></pre>
<p><strong>How <code>try/catch</code> maps to <code>.catch()</code>.</strong> When you use <code>try/catch</code> around an <code>await</code>, the engine transforms it into a <code>.catch()</code> handler on the Promise chain. A rejection becomes a thrown exception inside the async function:</p>
<pre><code><span class="lang-label">JavaScript</span>
<span class="comment">// This async/await code:</span>
<span class="keyword">async function</span> <span class="function">fetchData</span>() {
<span class="keyword">try</span> {
<span class="keyword">const</span> data = <span class="keyword">await</span> <span class="function">fetch</span>(<span class="string">"/api"</span>);
<span class="keyword">return</span> data;
} <span class="keyword">catch</span> (err) {
console.<span class="function">error</span>(err);
}
}
<span class="comment">// Is roughly equivalent to this Promise chain:</span>
<span class="keyword">function</span> <span class="function">fetchData</span>() {
<span class="keyword">return</span> <span class="function">fetch</span>(<span class="string">"/api"</span>)
.<span class="function">then</span>(data => data)
.<span class="function">catch</span>(err => console.<span class="function">error</span>(err));
}
</code></pre>
<div class="warning-box">
<div class="label">Common Gotcha: Forgetting to <code>await</code> (Fire-and-Forget)</div>
<p>If you call an async function without <code>await</code>, it returns a Promise that nobody is listening to. If that Promise rejects, you get an <strong>unhandled rejection</strong> -- one of the most common bugs in Node.js applications. The function still runs, but errors vanish silently:</p>
</div>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">async function</span> <span class="function">saveToDb</span>(data) {
<span class="keyword">await</span> db.<span class="function">insert</span>(data); <span class="comment">// might throw!</span>
}
<span class="comment">// BUG: no await -- if db.insert fails, we'll never know</span>
<span class="function">saveToDb</span>({ name: <span class="string">"Sean"</span> });
<span class="comment">// FIX: always await (or handle the returned Promise)</span>
<span class="keyword">await</span> <span class="function">saveToDb</span>({ name: <span class="string">"Sean"</span> });
</code></pre>
<h3>Sequential vs Parallel Execution Patterns</h3>
<p>One of the most impactful performance mistakes is accidentally running independent async operations sequentially when they could run in parallel:</p>
<pre><code><span class="lang-label">JavaScript</span>
<span class="comment">// SLOW: sequential -- each waits for the previous to finish</span>
<span class="comment">// Total time: time(A) + time(B) + time(C)</span>
<span class="keyword">const</span> a = <span class="keyword">await</span> <span class="function">fetchA</span>();
<span class="keyword">const</span> b = <span class="keyword">await</span> <span class="function">fetchB</span>();
<span class="keyword">const</span> c = <span class="keyword">await</span> <span class="function">fetchC</span>();
<span class="comment">// FAST: parallel -- all start at the same time</span>
<span class="comment">// Total time: max(time(A), time(B), time(C))</span>
<span class="keyword">const</span> [a, b, c] = <span class="keyword">await</span> Promise.<span class="function">all</span>([
<span class="function">fetchA</span>(),
<span class="function">fetchB</span>(),
<span class="function">fetchC</span>(),
]);
<span class="comment">// PARALLEL WITH ERROR ISOLATION: if one fails, you still get the others</span>
<span class="keyword">const</span> results = <span class="keyword">await</span> Promise.<span class="function">allSettled</span>([
<span class="function">fetchA</span>(),
<span class="function">fetchB</span>(),
<span class="function">fetchC</span>(),
]);
results.<span class="function">forEach</span>(r => {
<span class="keyword">if</span> (r.status === <span class="string">"fulfilled"</span>) console.<span class="function">log</span>(r.value);
<span class="keyword">else</span> console.<span class="function">error</span>(r.reason);
});
</code></pre>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">async function</span> <span class="function">fetchUser</span>(id) {
<span class="keyword">try</span> {
<span class="keyword">const</span> res = <span class="keyword">await</span> <span class="function">fetch</span>(<span class="string">`/api/users/${id}`</span>);
<span class="keyword">if</span> (!res.ok) <span class="keyword">throw</span> <span class="keyword">new</span> <span class="function">Error</span>(<span class="string">`HTTP ${res.status}`</span>);
<span class="keyword">return</span> <span class="keyword">await</span> res.<span class="function">json</span>();
} <span class="keyword">catch</span> (err) {
console.<span class="function">error</span>(<span class="string">"Failed to fetch user:"</span>, err);
<span class="keyword">throw</span> err;
}
}
<span class="comment">// Parallel fetches (don't await sequentially if independent!)</span>
<span class="keyword">const</span> [user, posts] = <span class="keyword">await</span> Promise.<span class="function">all</span>([
<span class="function">fetchUser</span>(<span class="number">1</span>),
<span class="function">fetchPosts</span>(<span class="number">1</span>),
]);
</code></pre>
</section>
<!-- ============================================================ -->
<section id="concurrency-control">
<h2>8. Async Patterns -- p-limit, Resource Pools & Concurrency Control</h2>
<p>In the previous section, we saw that <code>Promise.all()</code> runs everything in parallel. But what happens when "everything" is 1,000 HTTP requests, or 500 database queries? You will overwhelm the server, exhaust your connection pool, hit rate limits, or run out of file descriptors. This section is about the patterns that sit between "one at a time" (sequential) and "everything at once" (unbounded parallel).</p>
<h3>The Problem: Unbounded Concurrency</h3>
<p>Consider this seemingly reasonable code:</p>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">const</span> urls = <span class="function">Array</span>(<span class="number">1000</span>).<span class="function">fill</span>(<span class="keyword">null</span>).<span class="function">map</span>((_, i) => <span class="string">`https://api.example.com/item/${i}`</span>);
<span class="comment">// This fires ALL 1000 requests simultaneously</span>
<span class="keyword">const</span> results = <span class="keyword">await</span> Promise.<span class="function">all</span>(
urls.<span class="function">map</span>(url => <span class="function">fetch</span>(url).<span class="function">then</span>(r => r.<span class="function">json</span>()))
);
</code></pre>
<p>What goes wrong:</p>
<ul>
<li><strong>Server overwhelm:</strong> The target API gets 1,000 connections at once and starts returning 429 (Too Many Requests) or 503 errors</li>
<li><strong>Memory pressure:</strong> 1,000 in-flight HTTP responses with their buffers, headers, and parsed JSON all in memory simultaneously</li>
<li><strong>Connection limits:</strong> Browsers cap concurrent connections per origin (~6 in Chrome). Node.js has no hard limit but your OS does (file descriptor limits)</li>
<li><strong>Rate limiting:</strong> Most APIs enforce 10-100 requests/second. Blasting 1,000 at once gets you banned</li>
</ul>
<p>What you actually want is: run at most N tasks at the same time. When one finishes, start the next. This is <strong>concurrency control</strong>.</p>
<h3>What is p-limit?</h3>
<p><code>p-limit</code> is a popular npm package (by Sindre Sorhus) that limits the number of Promises running concurrently. The API is simple: you create a limiter with a concurrency number, then wrap your async functions with it:</p>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">import</span> pLimit <span class="keyword">from</span> <span class="string">"p-limit"</span>;
<span class="keyword">const</span> limit = <span class="function">pLimit</span>(<span class="number">5</span>); <span class="comment">// max 5 concurrent</span>
<span class="keyword">const</span> urls = <span class="function">Array</span>(<span class="number">1000</span>).<span class="function">fill</span>(<span class="keyword">null</span>).<span class="function">map</span>((_, i) => <span class="string">`https://api.example.com/item/${i}`</span>);
<span class="comment">// Only 5 fetches run at any given time</span>
<span class="keyword">const</span> results = <span class="keyword">await</span> Promise.<span class="function">all</span>(
urls.<span class="function">map</span>(url =>
<span class="function">limit</span>(() => <span class="function">fetch</span>(url).<span class="function">then</span>(r => r.<span class="function">json</span>()))
)
);
</code></pre>
<p>But how does it work? It is not magic. Let's build it from scratch.</p>
<h3>Building p-limit From Scratch</h3>
<p>The core idea is a <strong>semaphore</strong> -- a concurrency primitive that tracks how many operations are "active" and queues the rest. Here is a complete implementation with detailed comments explaining every line:</p>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">function</span> <span class="function">pLimit</span>(concurrency) {
<span class="comment">// Validate input</span>
<span class="keyword">if</span> (concurrency < <span class="number">1</span>) <span class="keyword">throw</span> <span class="keyword">new</span> <span class="function">RangeError</span>(<span class="string">"Concurrency must be >= 1"</span>);
<span class="comment">// The queue of functions waiting to run</span>
<span class="keyword">const</span> queue = [];
<span class="comment">// How many are currently running</span>
<span class="keyword">let</span> activeCount = <span class="number">0</span>;
<span class="comment">// Called when a task finishes -- tries to start the next queued task</span>
<span class="keyword">function</span> <span class="function">next</span>() {
activeCount--;
<span class="keyword">if</span> (queue.length > <span class="number">0</span>) {
<span class="comment">// Pull the next task off the queue and run it</span>
<span class="keyword">const</span> fn = queue.<span class="function">shift</span>();
<span class="function">fn</span>();
}
}
<span class="comment">// The "run" function: starts the task immediately</span>
<span class="keyword">function</span> <span class="function">run</span>(fn, resolve, reject) {
activeCount++;
<span class="comment">// Call the user's async function, then resolve/reject the wrapper Promise</span>
<span class="function">fn</span>().<span class="function">then</span>(resolve, reject).<span class="function">finally</span>(next);
}
<span class="comment">// The "enqueue" function: either runs immediately or queues</span>
<span class="keyword">function</span> <span class="function">enqueue</span>(fn, resolve, reject) {
<span class="keyword">if</span> (activeCount < concurrency) {
<span class="comment">// We have capacity -- run now</span>
<span class="function">run</span>(fn, resolve, reject);
} <span class="keyword">else</span> {
<span class="comment">// At capacity -- queue it for later</span>
queue.<span class="function">push</span>(() => <span class="function">run</span>(fn, resolve, reject));
}
}
<span class="comment">// The limiter function itself -- wraps user's fn in a Promise</span>
<span class="keyword">function</span> <span class="function">limit</span>(fn) {
<span class="keyword">return</span> <span class="keyword">new</span> <span class="function">Promise</span>((resolve, reject) => {
<span class="function">enqueue</span>(fn, resolve, reject);
});
}
<span class="comment">// Expose metadata for debugging</span>
Object.<span class="function">defineProperties</span>(limit, {
activeCount: { <span class="keyword">get</span>: () => activeCount },
pendingCount: { <span class="keyword">get</span>: () => queue.length },
});
<span class="keyword">return</span> limit;
}
</code></pre>
<p>Let's trace through what happens when you run 3 tasks with a concurrency of 2:</p>
<div class="example-box">
<div class="label">Execution Trace: pLimit(2) with 3 tasks</div>
<pre><code>limit(taskA) --> activeCount=0 < 2, run immediately. activeCount=1
limit(taskB) --> activeCount=1 < 2, run immediately. activeCount=2
limit(taskC) --> activeCount=2 >= 2, push to queue. queue=[taskC]
... taskA finishes ...
next() called: activeCount=1, queue has taskC
taskC starts. activeCount=2, queue=[]
... taskB finishes ...
next() called: activeCount=1, queue empty. Done.
... taskC finishes ...
next() called: activeCount=0, queue empty. All done.</code></pre>
</div>
<div class="tip-box">
<div class="label">Why Build It From Scratch?</div>
<p>Understanding the internals of p-limit teaches you the <strong>semaphore pattern</strong> -- one of the foundational concurrency primitives in all of computer science. The same pattern appears in Go (buffered channels), Java (<code>Semaphore</code>), Python (<code>asyncio.Semaphore</code>), and operating systems (POSIX semaphores). Once you understand this, you can solve any concurrency-limiting problem in any language.</p>
</div>
<h3>Resource Pool / Semaphore</h3>
<p>A resource pool is the next step up from p-limit. While p-limit controls <em>how many</em> tasks run, a resource pool manages <em>actual resources</em> -- database connections, API client instances, browser pages in Puppeteer, etc. The key difference: tasks "check out" a resource, use it, then "return" it.</p>
<p>Why does this pattern exist? Because many resources are expensive to create and have hard limits:</p>
<ul>
<li><strong>Database connections:</strong> PostgreSQL defaults to max 100 connections. Each connection consumes memory on the server. Opening a new TCP connection takes time (handshake, auth, TLS).</li>
<li><strong>API rate limits:</strong> External APIs often give you a fixed number of API keys or tokens. You need to reuse them, not create new ones.</li>
<li><strong>Browser instances:</strong> Puppeteer/Playwright browser pages consume 50-100MB each. You cannot open 500 at once.</li>
</ul>
<h3>Building a Resource Pool From Scratch</h3>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">class</span> ResourcePool {
<span class="function">constructor</span>(createFn, destroyFn, maxSize) {
<span class="keyword">this</span>.createFn = createFn; <span class="comment">// async () => resource</span>
<span class="keyword">this</span>.destroyFn = destroyFn; <span class="comment">// async (resource) => void</span>
<span class="keyword">this</span>.maxSize = maxSize;
<span class="keyword">this</span>.available = []; <span class="comment">// resources ready to be used</span>
<span class="keyword">this</span>.waiting = []; <span class="comment">// queued resolve functions</span>
<span class="keyword">this</span>.size = <span class="number">0</span>; <span class="comment">// total resources created</span>
}
<span class="keyword">async</span> <span class="function">acquire</span>() {
<span class="comment">// 1. If a resource is available, return it immediately</span>
<span class="keyword">if</span> (<span class="keyword">this</span>.available.length > <span class="number">0</span>) {
<span class="keyword">return</span> <span class="keyword">this</span>.available.<span class="function">pop</span>();
}
<span class="comment">// 2. If we haven't hit the limit, create a new one</span>
<span class="keyword">if</span> (<span class="keyword">this</span>.size < <span class="keyword">this</span>.maxSize) {
<span class="keyword">this</span>.size++;
<span class="keyword">try</span> {
<span class="keyword">return</span> <span class="keyword">await</span> <span class="keyword">this</span>.<span class="function">createFn</span>();
} <span class="keyword">catch</span> (err) {
<span class="keyword">this</span>.size--; <span class="comment">// creation failed, don't count it</span>
<span class="keyword">throw</span> err;
}
}
<span class="comment">// 3. At capacity -- wait for one to be released</span>
<span class="keyword">return</span> <span class="keyword">new</span> <span class="function">Promise</span>(resolve => {
<span class="keyword">this</span>.waiting.<span class="function">push</span>(resolve);
});
}
<span class="function">release</span>(resource) {
<span class="keyword">if</span> (<span class="keyword">this</span>.waiting.length > <span class="number">0</span>) {
<span class="comment">// Someone is waiting -- give the resource directly to them</span>
<span class="keyword">const</span> resolve = <span class="keyword">this</span>.waiting.<span class="function">shift</span>();
<span class="function">resolve</span>(resource);
} <span class="keyword">else</span> {
<span class="comment">// Nobody waiting -- put it back in the available pool</span>
<span class="keyword">this</span>.available.<span class="function">push</span>(resource);
}
}
<span class="comment">// Convenience: acquire, use, and automatically release</span>
<span class="keyword">async</span> <span class="function">use</span>(fn) {
<span class="keyword">const</span> resource = <span class="keyword">await</span> <span class="keyword">this</span>.<span class="function">acquire</span>();
<span class="keyword">try</span> {
<span class="keyword">return</span> <span class="keyword">await</span> <span class="function">fn</span>(resource);
} <span class="keyword">finally</span> {
<span class="keyword">this</span>.<span class="function">release</span>(resource);
}
}
<span class="comment">// Clean up all resources</span>
<span class="keyword">async</span> <span class="function">drain</span>() {
<span class="keyword">for</span> (<span class="keyword">const</span> resource <span class="keyword">of</span> <span class="keyword">this</span>.available) {
<span class="keyword">await</span> <span class="keyword">this</span>.<span class="function">destroyFn</span>(resource);
}
<span class="keyword">this</span>.available = [];
<span class="keyword">this</span>.size = <span class="number">0</span>;
}
}
</code></pre>
<h3>Using the Resource Pool</h3>
<pre><code><span class="lang-label">JavaScript</span>
<span class="comment">// Example: Database connection pool</span>
<span class="keyword">const</span> pool = <span class="keyword">new</span> <span class="function">ResourcePool</span>(
<span class="keyword">async</span> () => {
console.<span class="function">log</span>(<span class="string">"Creating new DB connection..."</span>);
<span class="keyword">return</span> <span class="keyword">await</span> <span class="function">createDbConnection</span>(<span class="string">"postgres://localhost/mydb"</span>);
},
<span class="keyword">async</span> (conn) => {
console.<span class="function">log</span>(<span class="string">"Closing DB connection..."</span>);
<span class="keyword">await</span> conn.<span class="function">close</span>();
},
<span class="number">10</span> <span class="comment">// max 10 connections</span>
);
<span class="comment">// Use it -- the pool handles acquire/release automatically</span>
<span class="keyword">const</span> user = <span class="keyword">await</span> pool.<span class="function">use</span>(<span class="keyword">async</span> (conn) => {
<span class="keyword">return</span> <span class="keyword">await</span> conn.<span class="function">query</span>(<span class="string">"SELECT * FROM users WHERE id = $1"</span>, [<span class="number">1</span>]);
});
<span class="comment">// Run 100 queries with only 10 connections</span>
<span class="keyword">const</span> userIds = <span class="function">Array</span>(<span class="number">100</span>).<span class="function">fill</span>(<span class="keyword">null</span>).<span class="function">map</span>((_, i) => i + <span class="number">1</span>);
<span class="keyword">const</span> users = <span class="keyword">await</span> Promise.<span class="function">all</span>(
userIds.<span class="function">map</span>(id =>
pool.<span class="function">use</span>(<span class="keyword">async</span> (conn) => conn.<span class="function">query</span>(<span class="string">"SELECT * FROM users WHERE id = $1"</span>, [id]))
)
);
<span class="comment">// At most 10 queries run at once. As each finishes, its connection</span>
<span class="comment">// is released back and picked up by the next waiting query.</span>
</code></pre>
<h3>Real-World Pattern: Rate-Limited API Calls</h3>
<p>Combining p-limit with delay gives you rate limiting -- critical for working with external APIs that enforce requests-per-second limits:</p>
<pre><code><span class="lang-label">JavaScript</span>
<span class="keyword">function</span> <span class="function">pLimitWithRate</span>(concurrency, minInterval) {
<span class="keyword">const</span> limit = <span class="function">pLimit</span>(concurrency);
<span class="keyword">let</span> lastRun = <span class="number">0</span>;
<span class="keyword">return</span> <span class="keyword">function</span>(fn) {
<span class="keyword">return</span> <span class="function">limit</span>(<span class="keyword">async</span> () => {
<span class="comment">// Ensure minimum time between requests</span>
<span class="keyword">const</span> now = Date.<span class="function">now</span>();
<span class="keyword">const</span> elapsed = now - lastRun;
<span class="keyword">if</span> (elapsed < minInterval) {
<span class="keyword">await</span> <span class="keyword">new</span> <span class="function">Promise</span>(r => <span class="function">setTimeout</span>(r, minInterval - elapsed));
}
lastRun = Date.<span class="function">now</span>();
<span class="keyword">return</span> <span class="function">fn</span>();