mirror of
https://github.com/Nezumi-2711/javascript-training.git
synced 2026-09-22 20:01:31 +00:00
Add more example about Asynchronous Programming
This commit is contained in:
@@ -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");
|
||||||
|
|||||||
Reference in New Issue
Block a user