Skip to content

Commit 0d45c6f

Browse files
committed
day 18
1 parent c8eab85 commit 0d45c6f

File tree

6 files changed

+2315
-10
lines changed

6 files changed

+2315
-10
lines changed

.gitignore

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@ day9.md
1414
day10.md
1515
01_02_03_days_backup.md
1616
test.md
17-
18_Day
1817
19_Day
1918
20_Day
2019
21_Day

18_Day/18_day_promise.md

Lines changed: 272 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,272 @@
1+
<div align="center">
2+
<h1> 30 Days Of JavaScript</h1>
3+
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
4+
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
5+
</a>
6+
<a class="header-badge" target="_blank" href="https://twitter.com/Asabeneh">
7+
<img alt="Twitter Follow" src="https://img.shields.io/twitter/follow/asabeneh?style=social">
8+
</a>
9+
10+
<sub>Author:
11+
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
12+
<small> January, 2020</small>
13+
</sub>
14+
15+
</div>
16+
17+
[<< Day 17](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/17_Day/17_day_web_storage.md) | [Day 19>>]()
18+
19+
![Thirty Days Of JavaScript](../images/banners/day_1_17.png)
20+
21+
- [Day 18](#day-18)
22+
- [Promise](#promise)
23+
- [Callbacks](#callbacks)
24+
- [Promise constructor](#promise-constructor)
25+
- [Fetch API](#fetch-api)
26+
- [Async and Await](#async-and-await)
27+
- [Exercises](#exercises)
28+
- [Exercises: Level 1](#exercises-level-1)
29+
- [Exercises: Level 2](#exercises-level-2)
30+
- [Exercises: Level 3](#exercises-level-3)
31+
32+
# Day 18
33+
34+
## Promise
35+
36+
We human give or receive a promise to do some activity at some point in time. If we keep the promise we make others happy but if we do not keep the promise, it may lead discontentment. Promise in JavaScript has something in common with the above examples.
37+
38+
A Promise is a way to handle asynchronous operations in JavaScript. It allows handlers with an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.
39+
40+
A Promise is in one of these states:
41+
42+
- pending: initial state, neither fulfilled nor rejected.
43+
- fulfilled: meaning that the operation completed successfully.
44+
- rejected: meaning that the operation failed.
45+
46+
A pending promise can either be fulfilled with a value, or rejected with a reason (error). When either of these options happens, the associated handlers queued up by a promise's then method are called. (If the promise has already been fulfilled or rejected when a corresponding handler is attached, the handler will be called, so there is no race condition between an asynchronous operation completing and its handlers being attached.)
47+
48+
As the Promise.prototype.then() and Promise.prototype.catch() methods return promises, they can be chained.
49+
50+
## Callbacks
51+
52+
To understand promise very well let us understand callback first. Let's see the following callbacks. From the following code blocks you will notice, the difference between callback and promises.
53+
54+
- call back
55+
Let us see a callback function which can take two parameters. The first parameter is err and the second is result. If the err parameter is false, there will not be error other wise it will return an error.
56+
57+
In this case the err has a value and it will return the err block.
58+
59+
```js
60+
//Callback
61+
const doSomething = callback => {
62+
setTimeout(() => {
63+
const skills = ['HTML', 'CSS', 'JS']
64+
callback('It did not go well', skills)
65+
}, 2000)
66+
}
67+
68+
const callback = (err, result) => {
69+
if (err) {
70+
return console.log(err)
71+
}
72+
return console.log(result)
73+
}
74+
75+
doSomething(callback)
76+
77+
```
78+
79+
```sh
80+
// after 2 seconds it will print
81+
It did not go well
82+
```
83+
84+
In this case the err is false and it will return the else block which is the result.
85+
86+
```js
87+
const doSomething = callback => {
88+
setTimeout(() => {
89+
const skills = ['HTML', 'CSS', 'JS']
90+
callback(false, skills)
91+
}, 2000)
92+
}
93+
94+
doSomething((err, result) => {
95+
if (err) {
96+
return console.log(err)
97+
}
98+
return console.log(result)
99+
})
100+
```
101+
102+
```sh
103+
// after 2 seconds it will print the skills
104+
["HTML", "CSS", "JS"]
105+
```
106+
107+
### Promise constructor
108+
109+
We can create a promise using the Promise constructor. We can create a new promise using the key word new followed by the word Promise and followed by a parenthesis. Inside the parenthesis it it takes a callback function. The promise callback function has two parameters which are the *resolve* and *reject* functions.
110+
111+
```js
112+
// syntax
113+
const promise = new Promise((resolve, reject) => {
114+
resolve('success')
115+
reject('failure')
116+
})
117+
```
118+
119+
```js
120+
// Promise
121+
const doPromise = new Promise((resolve, reject) => {
122+
setTimeout(() => {
123+
const skills = ['HTML', 'CSS', 'JS']
124+
if (skills.length > 0) {
125+
resolve(skills)
126+
} else {
127+
reject('Something wrong has happened')
128+
}
129+
}, 2000)
130+
})
131+
132+
doPromise
133+
.then(result => {
134+
console.log(result)
135+
})
136+
.catch(error => console.log(error))
137+
```
138+
139+
```sh
140+
["HTML", "CSS", "JS"]
141+
```
142+
143+
The above promise has been settled with resolve.
144+
Let us another example when the promise is settled with reject.
145+
146+
```js
147+
// Promise
148+
const doPromise = new Promise((resolve, reject) => {
149+
setTimeout(() => {
150+
const skills = ['HTML', 'CSS', 'JS']
151+
if (skills.indexOf('Node') !== -1) {
152+
resolve('fullstack developer')
153+
} else {
154+
reject('Something wrong has happened')
155+
}
156+
}, 2000)
157+
})
158+
159+
doPromise
160+
.then(result => {
161+
console.log(result)
162+
})
163+
.catch(error => console.log(error))
164+
```
165+
166+
```sh
167+
Something wrong has happened
168+
```
169+
170+
## Fetch API
171+
172+
The Fetch API provides an interface for fetching resources (including across the network). It will seem familiar to anyone who has used XMLHttpRequest, but the new API provides a more powerful and flexible feature set. In this challenge we will use fetch to request url and APIS. In addition to that let us see demonstrate use case of promises in accessing network resources using the fetch API.
173+
174+
```js
175+
const url = 'https://restcountries.eu/rest/v2/all' // countries api
176+
fetch(url)
177+
.then(response => response.json()) // accessing the API data as JSON
178+
.then(data => { // getting the data
179+
console.log(data)
180+
})
181+
.catch(error => console.log(error)) // handling error if something wrong happens
182+
```
183+
184+
## Async and Await
185+
186+
Async and await is an elegant way to handle promises. It is easy to understand and it clean to write.
187+
188+
```js
189+
const square = async function (n) {
190+
return n * n
191+
}
192+
193+
square(2)
194+
```
195+
196+
```sh
197+
Promise {<resolved>: 4}
198+
```
199+
200+
The word *async* in front of a function means that function will return a promise. The above square function instead of a value it returned a promise.
201+
202+
How do we access the value from the promise? To access the value from the promise, will use await.
203+
204+
```js
205+
const square = async function (n) {
206+
return n * n
207+
}
208+
const value = await square(2)
209+
```
210+
211+
```sh
212+
4
213+
```
214+
215+
Now, as you can see from the above example writing async in front of a function create a promise and to get the value from a promise we use await. Async and await go together, one can not exist without the other.
216+
217+
Let us fetch API data using both promise method and async and await method.
218+
219+
- promise
220+
221+
```js
222+
const url = 'https://restcountries.eu/rest/v2/all'
223+
fetch(url)
224+
.then(response => response.json())
225+
.then(data => {
226+
console.log(data)
227+
})
228+
.catch(error => console.log(error))
229+
```
230+
231+
- async and await
232+
233+
```js
234+
const fetchData = async () => {
235+
try {
236+
const response = await fetch(url)
237+
const countries = await response.json()
238+
console.log(countries)
239+
} catch (err) {
240+
console.log(err)
241+
}
242+
}
243+
console.log('===== async and await')
244+
fetchData()
245+
```
246+
247+
🌕 You are real and you kept your promise and your reached to day 18. Keep your promise and settle the challenge with resolve. You are 18 steps a head to your way to greatness. Now do some exercises for your brain and for your muscle.
248+
249+
## Exercises
250+
251+
```js
252+
const countriesAPI = 'https://restcountries.eu/rest/v2/all'
253+
const catsAPI = 'https://api.thecatapi.com/v1/breeds'
254+
```
255+
256+
### Exercises: Level 1
257+
258+
1. Read the countries API using fetch and print the name of country, capital, languages, population and area.
259+
260+
### Exercises: Level 2
261+
262+
1. Print out all the cat names in to catNames variable.
263+
264+
### Exercises: Level 3
265+
266+
1. Read the cats api and find the average weight of cat in metric unit.
267+
2. Read the countries api and find out the 10 largest countries
268+
3. Read the countries api and count total number of languages in the world used as officials.
269+
270+
🎉 CONGRATULATIONS ! 🎉
271+
272+
[<< Day 17](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/17_Day/17_day_web_storage.md) | [Day 19>>]()

0 commit comments

Comments
 (0)