Afrikaans
Akan
Albanian
Amharic
Arabic
Armenian
Azerbaijani
Basque
Belarusian
Bemba
Bengali
Bihari
Bosnian
Breton
Bulgarian
Cambodian
Catalan
Cebuano
Cherokee
Chichewa
Chinese (Simplified)
Chinese (Traditional)
Corsican
Croatian
Czech
Danish
Dutch
English
Esperanto
Estonian
Ewe
Faroese
Filipino
Finnish
French
Frisian
Ga
Galician
Georgian
German
Greek
Guarani
Gujarati
Haitian Creole
Hausa
Hawaiian
Hebrew
Hindi
Hmong
Hungarian
Icelandic
Igbo
Indonesian
Interlingua
Irish
Italian
Japanese
Javanese
Kannada
Kazakh
Kinyarwanda
Kirundi
Kongo
Korean
Krio (Sierra Leone)
Kurdish
Kurdish (Soranรฎ)
Kyrgyz
Laothian
Latin
Latvian
Lingala
Lithuanian
Lozi
Luganda
Luo
Luxembourgish
Macedonian
Malagasy
Malay
Malayalam
Maltese
Maori
Marathi
Mauritian Creole
Moldavian
Mongolian
Myanmar (Burmese)
Montenegrin
Nepali
Nigerian Pidgin
Northern Sotho
Norwegian
Norwegian (Nynorsk)
Occitan
Oriya
Oromo
Pashto
Polish
Portuguese (Brazil)
Portuguese (Portugal)
Punjabi
Quechua
Romanian
Romansh
Runyakitara
Russian
Samoan
Scots Gaelic
Serbian
Serbo-Croatian
Sesotho
Setswana
Seychellois Creole
Shona
Sindhi
Sinhalese
Slovak
Slovenian
Somali
Spanish
Spanish (Latin American)
Sundanese
Swahili
Swedish
Tajik
Tamil
Tatar
Telugu
Thai
Tigrinya
Tonga
Tshiluba
Tumbuka
Turkish
Turkmen
Twi
Uighur
Ukrainian
Urdu
Uzbek
Vietnamese
Welsh
Wolof
Xhosa
Yiddish
Yoruba
Zulu
1 1
So, we learned what AJAX and APIs are. 2
2
We used a bunch of asynchronous code already 3
3
and we learned all about promises. 4
4
But what's missing is to finally understand how all 5
5
of it really works behind the scenes of JavaScript. 6
6
And so let's find out. 7
7
And to start let's quickly review the JavaScript runtime 8
8
that we talked about way back in the course, 9
9
just to make sure that the rest of this lecture will make 10
10
sense to you. 11
11
So, a JavaScript runtime is basically a container 12
12
which includes all the different pieces 13
13
that are necessary to execute JavaScript code. 14
14
Now, the heart of every JavaScript runtime is the engine. 15
15
So, this is where code is actually executed 16
16
and where objects are stored in memory. 17
17
So, these two things happen in the call stack 18
18
and in the heap. 19
19
Now, what's important to note here is 20
20
that JavaScript has only one threat of execution. 21
21
And so it can only do one thing at a time. 22
22
There is absolutely no multitasking happening 23
23
in JavaScript itself. 24
24
Now, other languages like Java can execute multiple pieces 25
25
of code at the same time, but not JavaScript. 26
26
But anyway, next we have the web APIs environment. 27
27
These are some APIs provided to the engine, 28
28
but which are actually not part of 29
29
the JavaScript language itself. 30
30
So, that's things like the DOM timers 31
31
the fetch API, the geolocation API, and so on and so forth. 32
32
Next up, there is the callback queue 33
33
and this is a data structure that holds all the ready 34
34
to be executed callback functions that are attached 35
35
to some event that has occurred. 36
36
Finally, whenever the call stack is empty 37
37
the event loop takes callbacks from the callback queue 38
38
and puts them into call stack so that they can be executed. 39
39
So the event loop is the essential 40
40
piece that makes asynchronous behavior possible 41
41
in JavaScript. 42
42
It's the reason why we can have a 43
43
non blocking concurrency model in JavaScript. 44
44
And a concurrency model is simply how a language handles 45
45
multiple things happening at the same time. 46
46
But now how does this 47
47
non blocking concurrency actually work? 48
48
And why is the event loop so important? 49
49
Well, let's find out. 50
50
And let's focus on the essential parts of the runtime here. 51
51
So, that's the call stack the event loop the web APIs 52
52
and to callback queue. 53
53
So, as you know, by now, a JavaScript engine is built 54
54
around the idea of a single threat. 55
55
But if there was only one thread of execution in the engine 56
56
then how can asynchronous code be executed 57
57
in a non blocking way? 58
58
Well, that's actually the big question 59
59
that we're gonna answer in this video. 60
60
So, essentially you will learn 61
61
how the JavaScript concurrency model really works 62
62
behind the scenes, using all the parts of the 63
63
JavaScript runtime that you already know. 64
64
And as always, we will do this by looking 65
65
at a real code example. 66
66
So, let's walk through the code line 67
67
by line and I will keep updating the call stack as we go, 68
68
however, you already know how to call stack works. 69
69
And so it's best that you focus more 70
70
on the code and on the web APIs and callback queue. 71
71
Okay, but now let's start by selecting this image element. 72
72
And then in the next line 73
73
we set the source attribute of that image to dog.jpg. 74
74
And as we learned before this will now start to load 75
75
this image asynchronously in the background. 76
76
But this time we can actually understand 77
77
what that mysterious background actually is. 78
78
So, as you already know everything related to the DOM 79
79
is not really part of JavaScript, but of the web APIs. 80
80
And so it's in a web APIs environment where 81
81
the asynchronous tasks related to the DOM will run. 82
82
And in fact, the same is true for timers AJAX calls 83
83
and really all other asynchronous tasks. 84
84
So, again, these asynchronous tasks will all run 85
85
in the web API environment of the browser. 86
86
Now, if the image would be loading in a synchronous way 87
87
it would be doing so right in the call stack 88
88
blocking the execution of the rest of the code. 89
89
But, as we already learned, that would be terrible. 90
90
And that's why loading images in JavaScript is asynchronous. 91
91
So it does not happen in the call stack. 92
92
So, not in the main thread of execution, 93
93
but really in the web APIs environment 94
94
as I mentioned before. 95
95
Now, if we want to do something after the image 96
96
has finished loading, 97
97
then we need to listen to the load event. 98
98
And so that's exactly what we do in the next line of code. 99
99
So, here we attach an event listener 100
100
to the load event of that image 101
101
and pass an a callback function as always. 102
102
In practice, this means to register this callback 103
103
in the web APIs environment, 104
104
exactly where the image is loading. 105
105
And to callback will stay there 106
106
until the load event is emitted. 107
107
So, we're handling asynchronous behavior here 108
108
with a callback just as we learned before, 109
109
but anyway, let's go back to the code. 110
110
And so, in the next line, we make an AJAX call using 111
111
the fetch API. 112
112
And as always the asynchronous fetch operation will happen 113
113
in the web APIs environment. 114
114
And again, that's because otherwise we would be blocking 115
115
the call stack and create a huge lag in our application. 116
116
Finally, we use the then method on the promise returned 117
117
by the fetch function. 118
118
And this will also register a callback 119
119
in the web API environment so that we can react 120
120
to the future resolved value of the promise. 121
121
So this callback is associated with a promise 122
122
that is fetching the data from the API. 123
123
And that's gonna be important later on. 124
124
So, with this, we have now executed all the 125
125
top level of code. 126
126
So, all the code that is not inside any callback function 127
127
in asynchronous way. 128
128
We also have the image loading in the background 129
129
and some data being fetched from an API. 130
130
And so now it's time for this to get really interesting. 131
131
Let's say the image has finished loading 132
132
and therefore the load event is emitted on that image. 133
133
What happens next, 134
134
is that the callback for this event is put 135
135
into callback queue. 136
136
And the callback queue is basically an ordered list 137
137
of all the callback functions that are 138
138
in line to be executed. 139
139
And you can think of this callback queue, 140
140
as a to do list that you would write 141
141
for yourself with all the tasks that you have to complete. 142
142
So, the callback queue is also a to do list of a kind, 143
143
but with tasks that the call stack will eventually 144
144
have to complete. 145
145
Now, in this example, there are no other callbacks 146
146
in the queue yet, but there could be of course. 147
147
So, if there were already other callbacks waiting 148
148
in line, then this new callback would of course go straight 149
149
to the end of the queue. 150
150
And there it would sit patiently for its turn 151
151
to finally run. 152
152
And this actually has big implications. 153
153
So, imagine that you set a timer for five seconds. 154
154
And so after five seconds that timer's callback will be put 155
155
on the callback queue, right. 156
156
And let's say there were already other callbacks awaiting. 157
157
And let's also say that it took one second 158
158
to run all of those callbacks. 159
159
Then, in that case, your timers callback would only run 160
160
after six seconds and not after five. 161
161
So, these six seconds are the five seconds that passed 162
162
for the timer, plus the one second that it took 163
163
to run all the other callbacks that were already waiting 164
164
in line in front of your timer. 165
165
So, what this means is that the timers duration 166
166
that you define is not a guarantee. 167
167
The only guarantee is that the timers callback 168
168
will not run before five seconds, 169
169
but it might very well run after five seconds have passed. 170
170
So, it all depends on the state of the callback queue. 171
171
And also another queue that we're gonna learn about 172
172
in a second. 173
173
Now, another thing that's important to mention here 174
174
is that the callback queue also contains callbacks coming 175
175
from DOM events like clicks or key presses or whatever. 176
176
Now, we learned before that DOM events are not really 177
177
asynchronous behavior, but they still use the 178
178
callback queue to run their attached callbacks. 179
179
So, if a click happens on a button with addEventListener 180
180
then what will happen is just like what I illustrated here 181
181
with the asynchronous load event. 182
182
But anyway now it's time to finally learn about 183
183
the event loop. 184
184
So, here is what the event loop does. 185
185
It looks into the call stack and determines whether 186
186
it's empty or not. 187
187
Except of course for the global context, 188
188
then if the stack is indeed empty 189
189
which means that there's currently no code being executed 190
190
then it will take the first callback from the callback queue 191
191
and put it on the call stack two will be executed. 192
192
And this is called an event loop tick. 193
193
So each time the event loop takes a callback 194
194
from the callback queue. 195
195
We say that there was an event loop tick. 196
196
So, as we can see here the event loop 197
197
has the extremely important task 198
198
of doing coordination between the call stack 199
199
and to callbacks in the callback queue. 200
200
So, the event loop is basically who decides exactly 201
201
when each callback is executed. 202
202
We can also say that the event loop does the orchestration 203
203
of this entire JavaScript runtime. 204
204
Another thing that becomes clear from this whole explanation 205
205
is that the JavaScript language itself has actually 206
206
no sense of time. 207
207
That's because everything that is asynchronous 208
208
does not happen in the engine. 209
209
It's the runtime who manages all the asynchronous behavior. 210
210
And it's the event loop who decides 211
211
which code will be executed next. 212
212
But the engine itself simply executes 213
213
whatever code it has given. 214
214
Okay, so, this is of course, a lot to take in. 215
215
So let's try to recap what's happened here. 216
216
So, the image started loading asynchronously 217
217
in the web APIs environment 218
218
and not in the call stack, right. 219
219
We then used addEventListener to attach 220
220
a callback function to the image load event. 221
221
And this callback is basically or asynchronous code 222
222
it's code that we deferred into the future 223
223
because we only want to execute it once the image 224
224
has loaded. 225
225
And in the meantime, the rest of the code kept running. 226
226
Now addEventListener did not put the callback directly 227
227
in the callback queue. 228
228
It simply registered the callback, which then kept waiting 229
229
in the web APIs environment until the load event 230
230
was fired off. 231
231
Only then the environment put the call back into queue. 232
232
Then while in the queue the callback kept waiting 233
233
for the event loop to pick it up 234
234
and put it on the call stack. 235
235
And this happened as soon as the callback was first in line 236
236
and the call stack was empty. 237
237
And, that's it actually. 238
238
So, all this happened so that the image did not have to load 239
239
in the call stack, but in the background 240
240
in a non blocking way. 241
241
So, in a nutshell, the web APIs environment, 242
242
the callback queue 243
243
and the event loop, all together, make it possible 244
244
that asynchronous code can be executed in a non blocking way 245
245
even with only one thread of execution in the engine. 246
246
Wow, that was already a lot to understand, 247
247
but we're not done yet. 248
248
Because we still have to fetch function 249
249
getting data from the AJAX call in the background. 250
250
And this is basically happening with a promise. 251
251
Remember, now with promises things work in a slightly 252
252
different way which is why I included this promise example 253
253
as well. 254
254
So, let's say that the data has now finally arrived. 255
255
And so the fetch is done. 256
256
Now, callbacks related to promises 257
257
like this one that we registered with the 258
258
promises then method. 259
259
Do actually not go into the callback queue. 260
260
So, again this callback did we still have here, 261
261
which is coming from a promise will not be moved into the 262
262
callback queue. 263
263
Instead, callbacks of promises have a special queue 264
264
for themselves, which is the so called microtasks queue. 265
265
Now, what is special about the microtasks queue is 266
266
that it basically has priority over the callback queue. 267
267
So, at the end of an event loop tick, 268
268
so after a callback has been taken 269
269
from the callback queue, the event loop will check 270
270
if there are any callbacks in the microtasks queue. 271
271
And if there are, it will run all of them 272
272
before it will run any more callbacks 273
273
from the regular callback queue. 274
274
And, by the way, we call these callbacks 275
275
from promises microtasks. 276
276
And therefore the name microtasks queue. 277
277
And there are actually other microtasks 278
278
but that's not relevant here. 279
279
So going back to our example, 280
280
currently, we actually do have a microtask sitting 281
281
in a microtasks queue, the call stack is also empty. 282
282
And therefore the event loop will now take this callback 283
283
and put it in the call stack just like it does with 284
284
callbacks from the callback queue. 285
285
And it doesn't matter if the callback queue is empty or not. 286
286
So, this would have worked the exact same way 287
287
even if there were some callbacks in the callback queue. 288
288
And again, that's because microtasks always have priority. 289
289
In practice, this means that microtasks can basically 290
290
cut in line before all other regular callbacks. 291
291
Now, if one microtask adds a new microtask 292
292
then that new microtask is also executed 293
293
before any callbacks from the callback queue. 294
294
And this means that the microtasks queue 295
295
can essentially starve the callback queue. 296
296
Because if we keep adding more and more microtasks, 297
297
then callbacks in the callback queue can never execute. 298
298
Now, this is usually never a problem 299
299
but I just wanted to mention this possibility here anyways, 300
300
who knows maybe this will be an interview question 301
301
for you someday. 302
302
And if so, you'd now know the answer. 303
303
But anyway, as you can hopefully see the idea 304
304
of running asynchronous code with regular callbacks 305
305
and with microtasks coming from promises is very similar. 306
306
The only difference is that they go into different queues 307
307
and that the event loop gives microtasks priority 308
308
over regular callbacks. 309
309
All right, and thats finally it. 310
310
that's all you need to know about how 311
311
asynchronous JavaScript really works behind the scenes. 312
312
And I'm sure that this knowledge is gonna be 313
313
extremely helpful and valuable to you. 314
314
Because you're gonna be way more confident writing 315
315
asynchronous code now. 316
316
And also you will ace any job interview question 317
317
about asynchronous JavaScript. 318
318
And actually so many JavaScript developers don't know 319
319
anything about this. 320
320
So, I'm sure that this knowledge will put you 321
321
into the top 10% or even top 5% of JavaScript developers. 322
322
And that's just amazing on itself, right. 323
323
But anyway, let's no finish here 324
324
and try out some of this stuff in practice, 325
325
so that you see for yourself 326
326
that I didn't just make this stuff up.
Can't find what you're looking for?
Get subtitles in any language from opensubtitles.com, and translate them here.