diff --git a/Sample/asynchonous_programming/index.js b/Sample/asynchonous_programming/index.js index 1bc3526..0e09fb3 100644 --- a/Sample/asynchonous_programming/index.js +++ b/Sample/asynchonous_programming/index.js @@ -55,3 +55,46 @@ const getNewToDo = async () => { getNewToDo().then((data) => { console.log(">>> Data: ", data); }); + +const getJSON = (url, errorMsg = "Something went wrong") => { + return fetch(url).then((response) => { + if (!response.ok) throw new Error(`${errorMsg} (${response.status})`); + + return response.json(); + }); +}; + +const printInforCountry = (data) => { + console.log(`Native name: ${data.nativeName}`); + console.log(`Capital: ${data.capital}`); + console.log(`Population: ${data.population}`); +}; + +const getCountryData = function (country) { + // Country 1 + getJSON( + `https://countries-api-836d.onrender.com/countries/name/${country}`, + "Country not found!" + ) + .then((data) => { + printInforCountry(data[0]); + + const neighbour = data[0].borders?.[0]; + if (!neighbour) throw new Error("No neighbour found!"); + // Country 2 + return getJSON( + `https://countries-api-836d.onrender.com/countries/alpha/${neighbour}`, + "Country not found!" + ); + }) + .then((data) => { + console.log(`----------Neighbour Contry-----------`); + printInforCountry(data); + }) + .catch((err) => { + console.error(`Something went wrong 💥💥 ${err.message}. Try again!`); + }) + .finally(() => console.log("End!")); +}; + +getCountryData("vietnam");