-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path7_swapi.js
67 lines (54 loc) · 1.71 KB
/
7_swapi.js
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
// 7.- Hacer una petición a la swapi a una película y obtener sus personajes
const urlBase = 'https://swapi.dev/api/';
async function GetFilm(id) {
const url = `${urlBase}films/${id}`;
try{
const res = await fetch(url);
if(!res.ok) {
throw new Error(`HTTP error! Status: ${res.status}`);
}
const filmData = await res.json();
const filmDetails = {
name: filmData.title,
characters: [],
}
for(const characterUrl of filmData.characters) {
const characterDetails = await GetCharacters(characterUrl);
if(characterDetails) {
filmDetails.characters.push(characterDetails.name);
} else {
console.error(`Error fetching character details for ${characterUrl}`)
}
}
return filmDetails;
} catch(error) {
console.error(`Error: ${error.message}`);
return null;
}
}
async function GetCharacters(url) {
try {
const res = await fetch(url);
if(!res.ok) {
throw new Error(`HTTP error! Status: ${res.status}`);
}
const characterData = await res.json();
const characterDetails = {
name: characterData.name,
}
return characterDetails;
} catch(error) {
console.error(`Error: ${error.message}`);
return null;
}
}
GetFilm(3)
.then(filmDetails => {
if(filmDetails) {
console.log(`Film name: ${filmDetails.name}`);
console.log(`Characters:\n${filmDetails.characters.join('\n')}`);
}
})
.catch(error => {
console.error(`Error fetching details: ${error.message}`);
})