You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: README.md
+23-30Lines changed: 23 additions & 30 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,8 +1,8 @@
1
1
# 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:.
3
3
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:.
4
4
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
+
 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>
6
6
___
7
7
8
8
### Timing Events
@@ -23,7 +23,7 @@ The ***callback*** doesn’t immediately get added to the **call stack**, instea
23
23
clearTimeout(timerId);
24
24
```
25
25
26
-
A call to **setTimeout** returns a “timer identifier” ***timerId*** that we can use to cancel the execution.<br>
26
+
 A call to **setTimeout** returns a “timer identifier” ***timerId*** that we can use to cancel the execution.<br>
27
27
```javascript
28
28
let timerId =setTimeout(() =>console.log("never happens"), 1000);
29
29
console.log(timerId); // timer identifier
@@ -33,15 +33,15 @@ A call to **setTimeout** returns a “timer identifier” ***timerId*** that we
33
33
34
34
#### There are two ways of running something regularly.<br>
35
35
36
-
**setInterval** starts a function after the interval of time, then repeating to run a function continuously at that interval.<br>
36
+
 **setInterval** starts a function after the interval of time, then repeating to run a function continuously at that interval.<br>
37
37
```javascript
38
38
// repeat with the interval of 2 seconds
39
39
let intervalId =setInterval(() =>console.log('tick'), 2000);
Any function passed as the setImmediate() argument is a callback that's executed in the next iteration of the **event loop**.
72
+
 Any function passed as the setImmediate() argument is a callback that's executed in the next iteration of the **event loop**.
72
73
A ``setTimeout() callback`` with a 0ms delay is very similar to ``setImmediate()``. The execution order will depend on various factors.<br>
73
74
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
+
 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>
| pending ⏳ | means the operation is still running and the promise is pending ||
146
139
| fulfilled ✅ | the operation was completed and it was successful | .then() |
147
140
| rejected ❌ | the operation was completed but there was an error | .catch() |
148
141
| settled 🥳 | resolved or rejected, either way this callback gets called | .finally() |
149
142
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
+
 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.
151
144
152
145
```javascript
153
146
fetch( `some_api_url` ).then( (response) => { console.log('this will get called when the promise fulfills');
154
147
} ).catch( (error) => { console.log('this will get called when the promise is rejected');
155
148
} ).finally( () => { console.log('this will get called all the time'); } );
156
149
```
157
150
158
-
To handle errors with ``catch`` is best practice. Unhandled Promise rejections will crash your application with a fatal exception.<br>
151
+
 To handle errors with ``catch`` is best practice. Unhandled Promise rejections will crash your application with a fatal exception.<br>
159
152
160
153
```javascript
161
154
constfs=require('fs');
@@ -168,13 +161,13 @@ To handle errors with ``catch`` is best practice. Unhandled Promise rejections w
168
161
console.log('keep runing code');
169
162
```
170
163
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
+
 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.
@@ -183,13 +176,13 @@ Let's have a look at an example for fetching the json placeholder API to get som
183
176
.catch(err=>console.log(err));
184
177
```
185
178
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
+
 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.
187
180
188
181
___
189
182
### ES7 introduced Async/Await.
190
-
With the async and await keywords, we can create async functions which implicitly return a promise.<br>
183
+
 With the async and await keywords, we can create async functions which implicitly return a promise.<br>
191
184
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
+
 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_).
193
186
194
187
```javascript
195
188
functioncheckRequestCorrectness(request) {
@@ -209,8 +202,8 @@ When encountering an ``await`` keyword, the execution of the ``async function``
209
202
```
210
203
211
204
___
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
+
 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``!
213
206
214
207
___
215
-
Read more in the [section with code examples](https://github.com/SKindij/Asynchronous-JS-Nodejs/tree/main/codeApplication)...
208
+
 Read more in the [section with code examples](https://github.com/SKindij/Asynchronous-JS-Nodejs/tree/main/codeApplication)...
0 commit comments