-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
81 lines (71 loc) · 2.15 KB
/
Copy pathapp.js
File metadata and controls
81 lines (71 loc) · 2.15 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
78
79
80
81
// ******************************
// Sequential Axios Requests ******************************
// Example 1
console.log('Sequential Axios Requests')
// axios
// .get('https://swapi.dev/api/planets/')
// // If i just want the data i can use the destructuring her to grab the data out
// .then(({ data }) => {
// console.log(data)
// for (let planet of data.results) {
// console.log(planet.name)
// }
// // I could make a second request this way
// axios.get(data.next).then(({ data }) => {
// console.log(data)
// for (let planet of data.results) {
// console.log(planet.name)
// }
// })
// })
// ********************
// Example 2
/*
As we've seen, we can change .then by returning a promise so i don't have to
nest the .then like before
*/
// axios.get('https://swapi.dev/api/planets/').then(({ data }) => {
// console.log(data)
// for (let planet of data.results) {
// console.log(planet.name)
// }
// return axios.get(data.next)
// })
// .then(({ data }) => {
// console.log(data)
// for (let planet of data.results) {
// console.log(planet.name)
// }
// }).catch((err) => {
// console.log('ERROR!!', err);
// })
// ********************
// Example 3
/*
Refactor this in the same way that we created this nice chain of promises
where we just call a function each time and pass in a function name each
time to .then instead of having to use these inlie anonymous functions
*/
// fetchNextPlanets is just returning axios.get of the URL it returns
// the entire promise and that promise is resolved with the entire response
const fetchNextPlanets = (url = 'https://swapi.dev/api/planets/') => {
return axios.get(url)
}
// We need to manually resolve our promise, return a resolved promise
// which then calls the .then that is the ensuing .then
const printPlanets = ({ data }) => {
console.log(data)
for (let planet of data.results) {
console.log(planet.name)
}
return Promise.resolve(data.next)
}
fetchNextPlanets()
.then(printPlanets)
.then(fetchNextPlanets)
.then(printPlanets)
.then(fetchNextPlanets)
.then(printPlanets)
.catch((err) => {
console.log('ERR: ', err);
})