-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
64 lines (57 loc) · 2.3 KB
/
script.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
'use strict';
const btn = document.querySelector('.btn-country');
const countriesContainer = document.querySelector('.countries');
//////////////////////// The ES6 way of handling AJAX /////////////////////
const displayCountries = function (data, className = '') {
const html = `
<article class="country ${className}">
<img class="country__img" src="${data.flag}" />
<div class="country__data">
<h3 class="country__name">${data.name}</h3>
<h4 class="country__region">${data.region}</h4>
<p class="country__row"><span>👫</span>${(
data.population / 1000000
).toFixed(2)}M</p>
<p class="country__row"><span>🗣️</span>${data.languages[0].name}</p>
<p class="country__row"><span>💰</span>${
data.currencies[0].name
}</p>
</div>
</article>
`;
countriesContainer.insertAdjacentHTML('beforeend', html);
countriesContainer.style.opacity = 1;
};
//////////////////////Shorter ES6 Syntax /////////////////////////////
/*
const getCountryInfo = function (country) {
fetch(`https://restcountries.eu/rest/v2/name/${country}`)
.then(response => response.json())
.then(([data]) => {
const neighbour = data.borders[0];
//then method always return the promises so always return from last then()
return fetch(`https://restcountries.eu/rest/v2/alpha/${neighbour}`);
})
.then(response => response.json())
.then((data) => {
displayCountries(data, 'neighbour');
});
};
*/
///////////////////////My own Challenge Task//////////////////////////
const getCountryInfo = function (country) {
fetch(`https://restcountries.eu/rest/v2/name/${country}`)
.then(response => response.json())
.then(([data]) => {
displayCountries(data);
data.borders.forEach(neighbour =>
fetch(`https://restcountries.eu/rest/v2/alpha/${neighbour}`)
.then(response => response.json())
.then(data => displayCountries(data, 'neighbour'))
);
});
};
getCountryInfo('russia');
///////////////////////My Understanding of chaining and the challenge////
//Chaining promises mean that we have to return a fetch funtion from then()
//The challenge doesn't require long chaining so i used a loop as a callback