-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
77 lines (69 loc) · 2.13 KB
/
Copy pathapp.js
File metadata and controls
77 lines (69 loc) · 2.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// ******************************
// A Better Way Fetch ******************************
// Example 1
console.log('A Better Way Fetch')
// fetch('https://swapi.dev/api/planets/').then((response) => {
// fetch('https://swapi.dev/api/planets9999/')
// .then((response) => {
// console.log(response)
// // This response takes time
// // console.log(response.json())
// if (!response.ok) {
// console.log('ERROR NOT STATUS: 200', response.status)
// } else {
// response.json().then((data) => {
// // console.log(data);
// for (let planet of data.results) {
// console.log(planet.name)
// }
// })
// }
// })
// .catch((err) => {
// console.log('SOMETHING WHEN WRONG WIT FETCH!')
// console.log(err)
// })
// Example 2
// Throwing error to the .catch
fetch('https://swapi.dev/api/planets9999/')
.then((response) => {
if (!response.ok) {
throw new Error(`Status Code Error: ${response.status}`)
} else {
response.json().then((data) => {
// console.log(data);
for (let planet of data.results) {
console.log(planet.name)
}
})
}
})
.catch((err) => {
console.log('SOMETHING WHEN WRONG WIT FETCH!')
console.log(err)
})
// Compare FETCH with XMLHttpRequest()
// const firstReq = new XMLHttpRequest()
// firstReq.addEventListener('load', function () {
// console.log('First Request WORKED!!!')
// const data = JSON.parse(this.responseText)
// const filmURL = data.results[0].films[0]
// const filmReq = new XMLHttpRequest()
// filmReq.addEventListener('load', function() {
// console.log('Second Request WORKED!!!')
// console.log(this);
// const filmData = JSON.parse(this.responseText)
// console.log('filmData: ', filmData)
// })
// filmReq.addEventListener('error', function(e) {
// console.log('ERROR!!', e);
// })
// filmReq.open('GET', filmURL)
// filmReq.send()
// })
// firstReq.addEventListener('error', function () {
// console.log('ERROR!!!')
// })
// firstReq.open('GET', 'https://swapi.dev/api/planets/')
// firstReq.send()
// console.log('Request Sent!')