Skip to content

Commit 5b103dc

Browse files
committed
Initial day 9 contents
1 parent ea909b1 commit 5b103dc

File tree

5 files changed

+178
-0
lines changed

5 files changed

+178
-0
lines changed

day_09.md

+178
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,178 @@
1+
# [A walk in JavaScript](/README.md)
2+
3+
## DAY 9
4+
5+
- Asynchronous programming
6+
- Event Loop
7+
- Callback
8+
- Promises
9+
- Async/Await
10+
- .. good practices
11+
12+
## Asynchronous programming
13+
14+
Until ES6 (we'll get into that later, but we already saw a glimpse of that with Generators) there was nothing in the JS core specifying asynchronism, it had a fire-heated mark with the words "run-to-completion". In fact all asynchronous behavior depended on the host environment providing some kind of API in order to handle the asynchronism on it's side and communicate to the JavaScript engine the outcome if necessary.
15+
16+
For example, you will find references and definitions of **timers** on the MDN documentation for [WindowOrWorkerGlobalScope](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope) describing them in the context of a browser host environment but if you make a search of **timer** or **timeout** in the [ES6](https://www.ecma-international.org/ecma-262/6.0/) spec you'll find ... absolutely nothing! So what does it mean? Plain a simple, it means **JavaScript has no notion of timers**, the host does, and as we discussed in previous chapters, a web browser is not the only host for JavaScript, it's just one of many AND most likely this very environment host doesn't even have the code to perform the asynchronism, it acts just as a bridge to their own host which might happen to be an operative system!!!!
17+
18+
### Event Loop
19+
20+
One of this mechanisms to asynchronism is the **event-loop**, but what's that?
21+
22+
#### General definition
23+
24+
> In computer science, the **event loop**, **message dispatcher**, **message loop**, **message pump**, or **run loop** is a programming construct that waits for and dispatches [events](https://en.wikipedia.org/wiki/Event-driven_programming) or [messages](https://en.wikipedia.org/wiki/Message_Passing_Interface) in a [program](https://en.wikipedia.org/wiki/Computer_program). It works by making a request to some internal or external "event provider" (that generally [blocks](https://en.wikipedia.org/wiki/Blocking_(computing)) the request until an event has arrived), and then it calls the relevant [event handler](https://en.wikipedia.org/wiki/Event_handler) ("dispatches the event").
25+
>
26+
> Source: [Wikipedia - Event loop](https://en.wikipedia.org/wiki/Event_loop)
27+
28+
That was too dry, wasn't it?
29+
30+
Let's try with MDN.
31+
32+
> A JavaScript runtime uses a message queue, which is a list of messages to be processed. Each message has an associated function which gets called in order to handle the message.
33+
>
34+
> At some point during the event loop, the runtime starts handling the messages on the queue, starting with the oldest one. To do so, the message is removed from the queue and its corresponding function is called with the message as an input parameter. As always, calling a function creates a new stack frame for that function's use.
35+
>
36+
> The processing of functions continues until the stack is once again empty; then the event loop will process the next message in the queue (if there is one).
37+
>
38+
> Source: [MDN - Event Loop](https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop)
39+
40+
Ok that's better but still ... dry-ish.
41+
42+
Thankfully we have two invaluable resources to finally understand the event loop
43+
44+
- [What the heck is the event loop anyway?](https://www.youtube.com/watch?v=8aGhZQkoFbQ) | Philip Roberts | JSConf EU
45+
- [YDKJS - Async & Performance - Chapter 1: Asynchrony: Now & Later](https://github.com/getify/You-Dont-Know-JS/blob/1st-ed/async%20%26%20performance/ch1.md) | Kyle Simpson
46+
- [What you should know to really understand the Node.js Event Loop](https://medium.com/the-node-js-collection/what-you-should-know-to-really-understand-the-node-js-event-loop-and-its-metrics-c4907b19da4c) | Daniel Khan
47+
48+
---
49+
50+
### Callback
51+
52+
> A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.
53+
>
54+
> Here is a quick example:
55+
>
56+
>```javascript
57+
> function greeting(name) {
58+
> alert('Hello ' + name);
59+
>}
60+
>
61+
>function processUserInput(callback) {
62+
> var name = prompt('Please enter your name.');
63+
> callback(name);
64+
>}
65+
>
66+
>processUserInput(greeting);
67+
>```
68+
>
69+
> The above example is a synchronous callback, as it is executed immediately.
70+
>
71+
> Note, however, that callbacks are often used to continue code execution after an asynchronous operation has completed — these are called asynchronous callbacks. A good example is the callback functions executed inside a .then() block chained onto the end of a promise after that promise fulfills or rejects. This structure is used in many modern web APIs, such as fetch().
72+
>
73+
> Source: [MDN - Callback Function](https://developer.mozilla.org/en-US/docs/Glossary/Callback_function)
74+
75+
Let's take a look at a [general definition of callback on Wikipedia](https://en.wikipedia.org/wiki/Callback_(computer_programming))
76+
77+
Here an simplified example of callback you might have used but now you'll know better what id does.
78+
79+
```javascript
80+
setTimeout( () => console.log(`I'm running late...er`), 1000 );
81+
```
82+
83+
Can you describe, in your words like a bedtime story, what's happening with that code? Need a help with that? Let's move on and take a final step into this with [YDKJS - Async & Performance - Callbacks](https://github.com/getify/You-Dont-Know-JS/blob/1st-ed/async%20%26%20performance/ch2.md) | by Kyle Simpson
84+
85+
---
86+
87+
### Promises
88+
89+
Let's imagine we need to perform a task, you don't know how much it's gonna take but we need both make sure to do something whilst it's done AND in the meantime do something else AND have a complete control over the outcomes to prevent weir things happening.
90+
91+
If we do that with callbacks we'll end up in hell, actually there's a name for that, [callback hell](https://en.wiktionary.org/wiki/callback_hell), and there's even a [website](http://callbackhell.com/) with that name!
92+
93+
Let's make and example.
94+
95+
```javascript
96+
97+
setTimeout( () => {
98+
console.log(`A`);
99+
setTimeout( () => {
100+
console.log(`B`);
101+
setTimeout( () => {
102+
console.log(`C`);
103+
setTimeout( () => {
104+
console.log(`D`);
105+
}, 1000 );
106+
}, 100 );
107+
}, 0 );
108+
}, 5000 );
109+
110+
```
111+
112+
After a few moments thinking about it you might say "that's easy", I won't gent into the "using `console`" implications, but let's imagine that you need `B`to happen only if `A` is successful, AND `C`AND `D` should happen either way. Now our code starts looking not only hard to read but also hard to maintain, which is the doorway to a tsunami of bugs swarming to you.
113+
114+
So, what's a promise and why it might help here?
115+
116+
Imagine this:
117+
> I'm an Object, and once you give me a specific task I PROMISE YOU I'll let you know when I did it, telling wether I SUCCEEDED or FAILED providing you the summary (outcome) so you can use it, THEN you can do something with that info if I SUCCEEDED OR alternatively do something with my FAILURE. FINALLY you might want to do something either way.
118+
119+
That's something you are used to do with other people, isn't it?
120+
121+
Well, Promises work kinda that.
122+
123+
```javascript
124+
new Promise((resolve, reject) => {
125+
console.log('I started');
126+
resolve();
127+
})
128+
.then(() => {
129+
console.log(`A`);
130+
throw new Error('I failed in A');
131+
})
132+
.then(() => {
133+
console.log(`B`);
134+
})
135+
.catch((reason) => {
136+
console.log(reason);
137+
})
138+
.finally(() => {
139+
console.log(`C`);
140+
console.log(`D`);
141+
});
142+
143+
```
144+
145+
Easy to read, easy to control ... sort of, but definitely better than callback hell.
146+
147+
Too much talking, let go to the best sources you can get.
148+
149+
- [ECMAScript Promise Objects](https://www.ecma-international.org/ecma-262/6.0/#sec-promise-objects)
150+
- [ECMAScript Promise Constructor](https://www.ecma-international.org/ecma-262/6.0/#sec-promise-constructor)
151+
- [MDN - Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
152+
- [MDN - Using Promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises)
153+
- [YDKJS - Async & Performance - Chapter 3: Promises](https://github.com/getify/You-Dont-Know-JS/blob/1st-ed/async%20%26%20performance/ch3.md) | by Kyle Simpson
154+
155+
---
156+
157+
### Async/await
158+
159+
...
160+
161+
---
162+
163+
## Exercises
164+
165+
Let's open our test files:
166+
167+
- [event loop](/src/day_09/eventLoop.test.js)
168+
- [callback](/src/day_09/callback.test.js)
169+
- [promise](/src/day_09/promise.test.js)
170+
- [async/await](/src/day_09/asyncAwait.test.js)
171+
172+
Now open your terminal.
173+
174+
1. Make sure you're at the project location
175+
2. If you didn't install all the packages yet then run `npm i` for a fresh dependency install, or `npm ci` for an installation based on the lock file.
176+
3. Type `npm run test:watch`, this will start running your tests every time you make a change.
177+
178+
**Our task is to make ALL our DAY 9 tests pass ;)**

src/day_09/asyncAwait.test.js

Whitespace-only changes.

src/day_09/callback.test.js

Whitespace-only changes.

src/day_09/eventLoop.test.js

Whitespace-only changes.

src/day_09/promise.test.js

Whitespace-only changes.

0 commit comments

Comments
 (0)