Add more example about Asynchronous Programming

This commit is contained in:
2023-08-11 17:37:39 +07:00
parent 4b73bcdb07
commit 0b87729457
+43
View File
@@ -55,3 +55,46 @@ const getNewToDo = async () => {
getNewToDo().then((data) => { getNewToDo().then((data) => {
console.log(">>> Data: ", 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");