Skip to content

Commit 543433c

Browse files
authored
Update README.md
1 parent 8b40aed commit 543433c

File tree

1 file changed

+23
-30
lines changed

1 file changed

+23
-30
lines changed

README.md

Lines changed: 23 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
# Asynchronous programming in JavaScript and Node.js
2-
JavaScript is single-threaded: only one task can run at a time :turkey:.
2+
 JavaScript is single-threaded: only one task can run at a time :turkey:.
33
Browser gives us a **Web API** :lollipop: (DOM, setTimeout, HTTP requests, and so on). This can help us create some async, non-blocking behavior :eagle:.
44

5-
When we invoke a function, it gets added to the **call stack** :waffle: (_part of the JS engine, this isn’t browser specific_) - meaning that it’s first in, last out. When a function returns a value, it gets popped off the stack.<br>
5+
&emsp;When we invoke a function, it gets added to the **call stack** :waffle: (_part of the JS engine, this isn’t browser specific_) - meaning that it’s first in, last out. When a function returns a value, it gets popped off the stack.<br>
66
___
77

88
### Timing Events
@@ -23,7 +23,7 @@ The ***callback*** doesn’t immediately get added to the **call stack**, instea
2323
clearTimeout(timerId);
2424
```
2525

26-
A call to **setTimeout** returns a “timer identifier” ***timerId*** that we can use to cancel the execution.<br>
26+
&emsp;A call to **setTimeout** returns a “timer identifier” ***timerId*** that we can use to cancel the execution.<br>
2727
```javascript
2828
let timerId = setTimeout(() => console.log("never happens"), 1000);
2929
console.log(timerId); // timer identifier
@@ -33,15 +33,15 @@ A call to **setTimeout** returns a “timer identifier” ***timerId*** that we
3333

3434
#### There are two ways of running something regularly.<br>
3535

36-
**setInterval** starts a function after the interval of time, then repeating to run a function continuously at that interval.<br>
36+
&emsp;**setInterval** starts a function after the interval of time, then repeating to run a function continuously at that interval.<br>
3737
```javascript
3838
// repeat with the interval of 2 seconds
3939
let intervalId = setInterval(() => console.log('tick'), 2000);
4040
// after 7 seconds stop
4141
setTimeout(() => { clearInterval(intervalId); console.log('stop'); }, 7000);
4242
```
4343

44-
The other way is a **nested setTimeout**, like this:<br>
44+
&emsp;The other way is a **nested setTimeout**, like this:<br>
4545
```javascript
4646
let timerId = setTimeout(function tick() {
4747
console.log('tick');
@@ -50,7 +50,7 @@ The other way is a **nested setTimeout**, like this:<br>
5050
setTimeout(() => { clearTimeout (timerId); console.log('stop'); }, 7000);
5151
```
5252

53-
We can use the **clearInterval()** method to achieve a certain number of reruns of the function.<br>
53+
&emsp;We can use the **clearInterval()** method to achieve a certain number of reruns of the function.<br>
5454
```javascript
5555
let count = 0;
5656
const intervalId = setInterval(() => {
@@ -63,23 +63,25 @@ We can use the **clearInterval()** method to achieve a certain number of reruns
6363
```
6464

6565
---
66-
To execute some piece of code asynchronously use the **setImmediate()** function provided **by Node.js**:<br>
66+
67+
&emsp;To execute some piece of code asynchronously use the **setImmediate()** function provided **by Node.js**:<br>
6768
```javascript
6869
setImmediate( () => { console.log('run something'); } );
6970
```
7071

71-
Any function passed as the setImmediate() argument is a callback that's executed in the next iteration of the **event loop**.
72+
&emsp;Any function passed as the setImmediate() argument is a callback that's executed in the next iteration of the **event loop**.
7273
A ``setTimeout() callback`` with a 0ms delay is very similar to ``setImmediate()``. The execution order will depend on various factors.<br>
7374

74-
A function passed to **process.nextTick()** is going to be executed on the current iteration of the **event loop**, after the current operation ends. This means it will always execute before setTimeout and setImmediate.<br>
75+
&emsp;A function passed to **process.nextTick()** is going to be executed on the current iteration of the **event loop**, after the current operation ends. This means it will always execute before setTimeout and setImmediate.<br>
7576
```javascript
7677
process.nextTick( () => { console.log('do something'); } );
7778
```
7879

79-
It is the way the **JS** engine process a function **asynchronously** (after the current function), but as soon as possible, not queue it.
80+
&emsp;It is the way the **JS** engine process a function **asynchronously** (after the current function), but as soon as possible, not queue it.
8081
Use nextTick() when you want to make sure that in the next event loop iteration that code is already executed.<br>
8182

8283
---
84+
8385
#### The event loop executes tasks in the following order:<br>
8486
1. **call stack** (_...function()_)
8587
2. **microtask** queue (_ ...process.nextTick callback _)
@@ -106,7 +108,7 @@ Use nextTick() when you want to make sure that in the next event loop iteration
106108
___
107109
### ES6 introduced Promises.
108110

109-
We can create a promise, using a Promise constructor that receives a callback.<br>
111+
&emsp;We can create a promise, using a Promise constructor that receives a callback.<br>
110112
> *A Promise is an object that contains a status and a value.*
111113
```javascript
112114
new Promise ( () => { console.log('something') } );
@@ -115,7 +117,7 @@ We can create a promise, using a Promise constructor that receives a callback.<b
115117
> [[PromiseState]]: "pending"
116118
> [[PromiseResult]]: undefined
117119
118-
![promise-executing](https://github.com/SKindij/Asynchronous-JS-Nodejs/blob/main/codeApplication/promise-executor.jpg "promise-executing")
120+
&emsp; &emsp; &emsp; &emsp; ![promise-executing](https://github.com/SKindij/Asynchronous-JS-Nodejs/blob/main/codeApplication/promise-executor.jpg "promise-executing")
119121

120122
```javascript
121123
new Promise ( (resolve, reject) => resolve('oh yea, was res') );
@@ -131,31 +133,22 @@ We can create a promise, using a Promise constructor that receives a callback.<b
131133
> [[PromiseState]]: "rejected"
132134
> [[PromiseResult]]: "oh no, was rej"
133135
134-
135-
136-
137-
138-
139-
140-
141-
142-
143136
| STATE | DESCRIPTION | CALLBCAK |
144137
|:------------:|:---------------------------------------------------------------:|:----------:|
145138
| pending ⏳ | means the operation is still running and the promise is pending | |
146139
| fulfilled ✅ | the operation was completed and it was successful | .then() |
147140
| rejected ❌ | the operation was completed but there was an error | .catch() |
148141
| settled 🥳 | resolved or rejected, either way this callback gets called | .finally() |
149142

150-
Typically **promise** is used to manage situations where you must wait for the outcome of an operation. *For example, uploading files to the server and awaiting the response of an API call, or just asking the user to choose a file from their computer.* A **promise** is simply a function that returns an Object which you can attach callbacks to. These callbacks will have to wait until the operation is ``fulfilled`` or ``rejected``, and will only get called when the operation has completed.
143+
&emsp;Typically **promise** is used to manage situations where you must wait for the outcome of an operation. *For example, uploading files to the server and awaiting the response of an API call, or just asking the user to choose a file from their computer.* A **promise** is simply a function that returns an Object which you can attach callbacks to. These callbacks will have to wait until the operation is ``fulfilled`` or ``rejected``, and will only get called when the operation has completed.
151144

152145
```javascript
153146
fetch( `some_api_url` ).then( (response) => { console.log('this will get called when the promise fulfills');
154147
} ).catch( (error) => { console.log('this will get called when the promise is rejected');
155148
} ).finally( () => { console.log('this will get called all the time'); } );
156149
```
157150

158-
To handle errors with ``catch`` is best practice. Unhandled Promise rejections will crash your application with a fatal exception.<br>
151+
&emsp;To handle errors with ``catch`` is best practice. Unhandled Promise rejections will crash your application with a fatal exception.<br>
159152

160153
```javascript
161154
const fs = require('fs');
@@ -168,13 +161,13 @@ To handle errors with ``catch`` is best practice. Unhandled Promise rejections w
168161
console.log('keep runing code');
169162
```
170163

171-
The ``.then()`` callback is not really the end. That's because when you return value of a promise you get another promise. This becomes very useful when you want to run a series of asynchronous operations in order. All you have to do is to return the value of the promise.
164+
&emsp;The ``.then()`` callback is not really the end. That's because when you return value of a promise you get another promise. This becomes very useful when you want to run a series of asynchronous operations in order. All you have to do is to return the value of the promise.
172165

173166
```javascript
174167
Promise.resolve(1981).then(res => 2023 - res).then(res => 50 - res).then(res => 2023 + res).then(res => console.log(res) );
175168
```
176169

177-
Let's have a look at an example for fetching the json placeholder API to get some todos.
170+
&emsp;Let's have a look at an example for fetching the json placeholder API to get some todos.
178171

179172
```javascript
180173
fetch('https://jsonplaceholder.typicode.com/todos')
@@ -183,13 +176,13 @@ Let's have a look at an example for fetching the json placeholder API to get som
183176
.catch(err => console.log(err));
184177
```
185178

186-
We ``fetch`` some JSON data via an HTTP request. The **fetch function** returns a **promise**, which will either ``resolve`` or ``reject``. The **response body** has a json method for parsing the response from JSON to an object. ``.then`` returns a promise of its own, which handle by attaching another ``.then`` handler, and in case of **error** we attach a ``catch`` handler and log the error.
179+
&emsp;We ``fetch`` some JSON data via an HTTP request. The **fetch function** returns a **promise**, which will either ``resolve`` or ``reject``. The **response body** has a json method for parsing the response from JSON to an object. ``.then`` returns a promise of its own, which handle by attaching another ``.then`` handler, and in case of **error** we attach a ``catch`` handler and log the error.
187180

188181
___
189182
### ES7 introduced Async/Await.
190-
With the async and await keywords, we can create async functions which implicitly return a promise.<br>
183+
&emsp;With the async and await keywords, we can create async functions which implicitly return a promise.<br>
191184

192-
When encountering an ``await`` keyword, the execution of the ``async function`` body gets paused ✋🏼. And the rest of the ``async function`` gets run in a **microtask** instead of a regular task. In that time the ***JS engine*** jumps out of the async function and continues running the code in the ***execution context*** in which the async function got called 🏃🏽‍♀️ (_for example, the global execution context_).
185+
&emsp;When encountering an ``await`` keyword, the execution of the ``async function`` body gets paused ✋🏼. And the rest of the ``async function`` gets run in a **microtask** instead of a regular task. In that time the ***JS engine*** jumps out of the async function and continues running the code in the ***execution context*** in which the async function got called 🏃🏽‍♀️ (_for example, the global execution context_).
193186

194187
```javascript
195188
function checkRequestCorrectness(request) {
@@ -209,8 +202,8 @@ When encountering an ``await`` keyword, the execution of the ``async function``
209202
```
210203

211204
___
212-
Did you notice how **async functions** are different compared to a **promise.then**? The ``await`` keyword suspends the ``async function``, whereas the ``Promise`` body would've kept on being executed if we would've used ``.then``!
205+
&emsp;Did you notice how **async functions** are different compared to a **promise.then**? The ``await`` keyword suspends the ``async function``, whereas the ``Promise`` body would've kept on being executed if we would've used ``.then``!
213206

214207
___
215-
Read more in the [section with code examples](https://github.com/SKindij/Asynchronous-JS-Nodejs/tree/main/codeApplication)...
208+
&emsp;Read more in the [section with code examples](https://github.com/SKindij/Asynchronous-JS-Nodejs/tree/main/codeApplication)...
216209

0 commit comments

Comments
 (0)