Skip to content

Commit

Permalink
moved Javascript 3 explanations from AMS to the study book
Browse files Browse the repository at this point in the history
  • Loading branch information
robvk committed Mar 1, 2021
1 parent c8a4a7d commit 8dbde4f
Show file tree
Hide file tree
Showing 10 changed files with 357 additions and 30 deletions.
4 changes: 4 additions & 0 deletions _sidebar.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@
- [What is a browser?](/the-internet/browser.md)
- [What is the DOM?](/the-internet/dom.md)
- [DOM Manipulation](/the-internet/dom-manipulation.md)
- [Event Loop](/the-internet/event-loop.md)
- [API](/the-internet/api.md)
- [Fetch](/the-internet/fetch.md)
- [HTML & CSS](/html-css/README.md)
- [HTML](/html-css/html.md)
- [CSS](/html-css/css.md)
Expand All @@ -50,6 +53,7 @@
- [Functional Programming](/javascript/functional-programming.md)
- [OOP](/javascript/oop.md)
- [Asynchronous](/javascript/asynchronous.md)
- [Promises](/javascript/promises.md)
- [Node.js](/node-js/README.md)
- [REPL](/node-js/repl.md)
- [Getting Started](/node-js/getting-started.md)
Expand Down
Binary file added javascript/assets/javascript-sync-vs-async.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
75 changes: 46 additions & 29 deletions javascript/asynchronous.md
Original file line number Diff line number Diff line change
@@ -1,31 +1,48 @@
# Asynchronous JS

## The Event Loop

* [Loupe](http://latentflip.com/loupe/) +10
* [Visualizing the Event Loop](https://dev.to/lydiahallie/javascript-visualized-event-loop-3dif)
* [Understanding Asynchronous JS](https://blog.bitsrc.io/understanding-asynchronous-javascript-the-event-loop-74cd408419ff)
* [javascript.info/settimeout-setinterval](https://javascript.info/settimeout-setinterval)

## Promises

* Visualize Promises: [Promisees](https://bevacqua.github.io/promisees/), [PromiseTree](https://shlomiassaf.github.io/PromiseTree/playground/#/playground), [dev.to/lydiahallie](https://dev.to/lydiahallie/javascript-visualized-promises-async-await-5gke)
* [Awesome Promises](https://github.com/wbinnssmith/awesome-promises)
* [Promise Cookbook](https://github.com/mattdesl/promise-cookbook)
* [Coding Train](https://www.youtube.com/watch?v=QO4NXhWo_NM&list=PLRqwX-V7Uu6bKLPQvPRNNE65kBL62mVfx)
* [javascript.info/async](https://javascript.info/async)
* [Promises in 10 minutes](https://www.youtube.com/watch?v=DHvZLI7Db8E)
* [Async JS Crash Course](https://www.youtube.com/watch?v=PoRJizFvM7s)
* [Promise Basics](https://javascript.info/promise-basics)
* Examples to Study: [egghead-javascript-promises](https://github.com/mariusschulz/egghead-javascript-promises)
* [Traversy: Asynchronous Programming](https://www.youtube.com/watch?v=PoRJizFvM7s)
* [__promises__: FunFunFunction](https://www.youtube.com/watch?v=2d7s3spWAzo&list=PL0zVEGEvSaeEd9hlmCXrk5yUyqUag-n84)
* [__async/await__: FunFunFunction](https://www.youtube.com/watch?v=568g8hxJJp4)

## Closure

[Closure in Javascript](https://www.youtube.com/watch?v=71AtaJpJHw0&t=7s)
[Closures in JavaScript | Inside a loop, inner function and setTimeoout](https://www.youtube.com/watch?v=-xqJo5VRP4A)

## Fetch API
[Learn Fetch API In 6 Minutes](https://www.youtube.com/watch?v=cuEtnrL9-H0&list=PLfK7GzSJCtQz1ibcScVAGuOGUpdsIVuo3&index=12&t=0s)
## Synchronous vs. asynchronous

### Synchronous

In the past you've learned about **control flow**. In short: it's the order in which the computer executes statements in a script. In JavaScript this goes from left to right, top to bottom.

Let's look at code execution from another angle. The program that executes your code can do it in two basic ways: synchronous or asynchronous. Whenever code blocks are executed line after line (from top to bottom) we call this **synchronous execution**. However, when code blocks can be executed **without having to wait until a command ends**, we call this **asynchronous execution**. This is illustrated in the following diagram:

![Sync vs. Async](./assets/javascript-sync-vs-async.png)

Now imagine the following scenario:

> Noer wants to have breakfast but he doesn't have any food at home. He decides he want to eat oatmeal. The ingredients (oats and milk) can be bought at the supermarket. How to do this? First Noer takes a shower. Then he puts on some clothes. Then some shoes. Then he opens the door and goes outside. Then he jumps on the bike and goes to the closest supermarket. After looking for some time he finds the ingredients. Then Noer buys the ingredients. Then he jump back on the bike and go home. Then he mixes the ingredients and makes oatmeal. Then Noer eats and feels amazing!
In this example, each action could only happen after the previous has been completed. Noer can't put on his shoes, while taking a shower. Or, he can't eat oatmeal while he buys the ingredients.

As you can see, each action is executed in a synchronous manner. This is to say: in a logical order sequentially and only one action at a time.

**This is also how JavaScript by default operates**. Only one operation can happen at a time. If something else wants to start, it has to wait until the current action has finished.

### Asynchronous

Sometimes we want to do multiple things at the same time, without each action to be dependent on each other. Asynchronous execution avoids this bottleneck. You are essentially saying, “I know this function call is going to take a great deal of time, but my program doesn’t want to wait around while it executes.” Consider the following scenario:

> Wouter is feeling hungry, so he decides to go to a restaurant. He arrives there and gets into the line to order food. After ordering he takes a seat and, while he waits, reads a book. Occassionally he looks around and sees different things happening: new people enter the restaurant, some people get their food served and others are just talking. After a short while Wouter's food arrives and it's time to dig in!
In this example Wouter reads a book, but that doesn't affect his meal from being prepared. While his meal is prepared there are other people walking around, eating or just talking with each other. In short: multiple things are happening simultaneously and every event is not dependent upon another.

This does not happen by default in JavaScript, and needs to be invoked. A way to do that is by using `callbacks`, which you'll be learning about in the next section.

### Introducing asynchronicity using callbacks

Imagine the following situation:

> It's 15.00 and you're studying at home for an exam on the next day. Suddenly, your phone rings. You pick up and find it's your best friend! They ask if you'd like to hang out later. What do you do? On the one hand, you'd love to hang out have fun. On the other hand, you really should study some more. You don't know so you tell your friend that you're going to _call back_ later with your answer. You end the conversation and go back to studying. Maybe you take a break or have a snack as well. On the other line your friend hangs up the phone and continues along with their day: they go out grocery shopping, cleaning the house and cooking dinner. After finishing your studies you call your friend and makes plans to go out together.
This example illustrates the concept of **asynchronicity**: there are multiple processes happening simultaneously, without any single thing being dependent upon another. Your friend is not waiting by the phone until you have the answer. Or in technical terms: until the callback (which is you) has the return value (the answer to your friend's request to hang out).

This is the utility of `callbacks`: they allow us to introduce asynchronicity into the control flow of an application.

Study the following resources to learn more about the importance of callbacks:

- [Asynchronous JavaScript](https://www.youtube.com/watch?v=YxWMxJONp7E)
- [Understanding JavaScript Callbacks](https://www.youtube.com/watch?v=Nau-iEEgEoM)
- [Callback Functions](https://www.youtube.com/watch?v=QRq2zMHlBz4)

4 changes: 3 additions & 1 deletion javascript/closures.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,6 @@ If you just can't get enough, here are some extra links that mentors/students ha
- [The Ultimate Guide to Execution Contexts, Hoisting, Scoping and Closures in JavaScript](https://www.youtube.com/watch?v=Nt-qa_LlUH0)
- [Understanding Closures](https://www.youtube.com/watch?v=rBBwrBRoOOY)
- [Master the JavaScript interview: what is a closure](https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-closure-b2f0d2152b36)
- [I never understood JavaScript closures](https://medium.com/dailyjs/i-never-understood-javascript-closures-9663703368e8)
- [I never understood JavaScript closures](https://medium.com/dailyjs/i-never-understood-javascript-closures-9663703368e8)
- [Closure in Javascript](https://www.youtube.com/watch?v=71AtaJpJHw0&t=7s)
- [Closures in JavaScript | Inside a loop, inner function and setTimeoout](https://www.youtube.com/watch?v=-xqJo5VRP4A)
54 changes: 54 additions & 0 deletions javascript/modern-js.md
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,60 @@ showResult(name, subject, grade);

Note that we can even have default values while destructuring an array like we did with the subject in the example above!

## Async / await
If you have not learned anything about Promises yet, skip this part for now and wait until you understand that. This is a quite advanced addition to the modern JS repetoire.

Async/await is syntax to help make callbacks more readable. Here's what async/await might look in action:

```js
async fetchData () {
const fetchedData = await fetch('https://randomuser.me/api/');
const parsedData = await fetchedData.json();
return parsedData;
}
```

How do we use it? We put the keyword `async` in front of the function declaration that will contain asynchronous code. Then in every line that returns a Promise we put the keyword `await` in front. That's it. Now the function will wait for the return of the fetch promise and grabbing the data before continuing to the next line.

### Catching errors in async/await
As you might have noticed, the `async/await` keywords don't give us a way catching errors like it does in the Promise object.

But before we get into that, we should define "catching errors" a little bit. By "catching errors" we mean:

1. that a line of code has caused an error (because of incorrect syntax or data type)
2. that the program has shutdown to prevent any other errors from happening
3. that the application gives feedback to the developer and/or user about where the error came from

In the Promise object, we can use the function `catch` to take care of errors. It takes in a callback, which automatically receives an error object. Here's an example:

```js
Promise.catch(function(error) {
console.log(error);
});
```

With the `async/await` keywords, we don't get a `catch` function to use. So instead we have to use some other solution: the `try... catch` block. It's also an addition to the language, given to us by **ECMAScript 6**:

```js
// This function will run. If anything goes wrong...
async fetchData () {
try {
const fetchedData = await fetch('https://randomuser.me/api/');
const parsedData = await fetchedData.json();
return parsedData;
} catch (err) {
// ...the code in this block will execute. The error that has been created will now be inserted into `err`
console.log('Oops, something went wrong!', err);
}
}
```

### Extra reading about Async/await
- [The Evolution of Callbacks, Promises & Async/Await](https://www.youtube.com/watch?v=gB-OmN1egV8)
- [Async JS Crash Course - Callbacks, Promises, Async/Await](https://www.youtube.com/watch?v=PoRJizFvM7s)
- [JavaScript Try Catch & Error Handling ES6 Tutorial](https://www.youtube.com/watch?v=ye-aIwGJKNg)
- [Error handling, "try..catch"](https://javascript.info/try-catch)

# Extra reading
If you just can't get enough, here are some extra links that mentors/students have found useful concerning this topic:

Expand Down
87 changes: 87 additions & 0 deletions javascript/promises.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
# Promises

For a video run through of what Promises are, look no further than the following video. There may be some syntax and concepts in there that you have not seen before (xhr request, axios) but those are used as an example for the promises:

{% hyf-youtube src="https://www.youtube.com/watch?v=MftH4t9vz7A" %}

## Callback Hell

By now you should've had some practice using callbacks. To reiterate, we use callbacks **as a way to create asynchronicity** in our application: we want to enable our application to do multiple things simultaneously.

But what if you want to have callbacks within callbacks... within callbacks? This will lead to what is known as **callback hell**.

- [Callback Hell](http://callbackhell.com/)

This is where `Promises` come in. The idea of the `Promise` is a product of the evolution within the JavaScript language. A bunch of JavaScript developers wanted to figure out how to solve the problem of callback hell and this is what they came up with. Here's a basic example:

```js
const promise = new Promise(function(resolve, reject) {
if (true) {
resolve('It has succeeded!');
} else {
reject('It has failed...');
}
});
```

## Promise States

A promise can be in 1 of 3 states:

1. Pending: The asynchronous code is being executed, with no result yet
2. Fulfilled (resolved): The asynchronous code has successfully been executed without problems
3. Rejected: The asynchronous code has failed because of some error

When a Promises is executed it will first execute the asynchronous code inside. In this process it will go into the `pending` state. After, depending on if it succeeded or not, it will be `resolved` or `rejected`.

## Chaining

What if you need to perform several asynchronous operations, that depend on the result of the one that came before it? For that we can use the `.then()` method: a special function, given to us by the Promise object, that allows us to directly use the return value of the asynchronous operation that happened before. Here's an example:

```js
new Promise(function(resolve, reject) {
setTimeout(() => resolve(1), 1000); // We wait 1 second and then resolve with value 1
})
.then(function(result) {
console.log(result); // Result: 1
return result * 2;
})
.then(function(result) {
alert(result); // Result: 2
return result * 2;
})
.catch(error => {
console.log(error);
});
```

By chaining the Promise we can gain greater control over the results of our asynchronous operations!

## Benefits

The concept of a Promise, in execution, doesn't add anything new. It does exactly what callbacks aim to do, which is enabling `asynchronous actions`: for example, clicking a button to load in an image, while still being able to navigate the webpage.

So what are the benefits of using a Promise over a callback? Here's a few:

1. It makes writing asynchronous JavaScript code more readable for you, the developer. In effect, you could call Promises the updated version of callbacks. Callbacks version 2.0.
2. Better error handling, because of the `catch` block attached at the end. When something goes wrong within the Promise structure, it will throw an error. This error will then be caught and handled within the `catch` block.

# Extra reading
If you just can't get enough, here are some extra links that mentors/students have found useful concerning this topic:

* [JavaScript Promises for Dummies](https://scotch.io/tutorials/javascript-promises-for-dummies)
* [Let's learn ES6 - Promises](https://www.youtube.com/watch?v=vQ3MoXnKfuQ)
* [JavaScript Promise in 100 Seconds](https://www.youtube.com/watch?v=RvYYCGs45L4)
* [A Simple Guide to ES6 Promises](https://codeburst.io/a-simple-guide-to-es6-promises-d71bacd2e13a)
* Visualize Promises: [Promisees](https://bevacqua.github.io/promisees/), [PromiseTree](https://shlomiassaf.github.io/PromiseTree/playground/#/playground), [dev.to/lydiahallie](https://dev.to/lydiahallie/javascript-visualized-promises-async-await-5gke)
* [Awesome Promises](https://github.com/wbinnssmith/awesome-promises)
* [Promise Cookbook](https://github.com/mattdesl/promise-cookbook)
* [Coding Train](https://www.youtube.com/watch?v=QO4NXhWo_NM&list=PLRqwX-V7Uu6bKLPQvPRNNE65kBL62mVfx)
* [javascript.info/async](https://javascript.info/async)
* [Promises in 10 minutes](https://www.youtube.com/watch?v=DHvZLI7Db8E)
* [Async JS Crash Course](https://www.youtube.com/watch?v=PoRJizFvM7s)
* [Promise Basics](https://javascript.info/promise-basics)
* Examples to Study: [egghead-javascript-promises](https://github.com/mariusschulz/egghead-javascript-promises)
* [Traversy: Asynchronous Programming](https://www.youtube.com/watch?v=PoRJizFvM7s)
* [__promises__: FunFunFunction](https://www.youtube.com/watch?v=2d7s3spWAzo&list=PL0zVEGEvSaeEd9hlmCXrk5yUyqUag-n84)
* [__async/await__: FunFunFunction](https://www.youtube.com/watch?v=568g8hxJJp4)
Loading

0 comments on commit 8dbde4f

Please sign in to comment.