[JavaScript] Asynchronous JavaScript: Promises, Async/Await, and AJAX - Throwing Error Manually
Creating generic function
const getJSON = function (url, errorMsg = 'Something went wrong') {
return fetch(url).then(response => {
if (!response.ok) throw new Error(`${errorMsg} (${response.status})`);
return response.json();
});
};
Throwing error manually ('Country not found' error)
const getCountryData = function (country) {
// country 1
getJSON(`https://restcountries.com/v2/name/${country}`, 'Country not found')
.then(data => {
renderCountry(data[0]);
const neighbor = data[0].borders?.[0]; // optional chaining for no borders
if (!neighbor) throw new Error('No neighbor found');
//country 2 (flat chain)
return getJSON(
`https://restcountries.com/v2/alpha/${neighbor}`,
'Country not found'
);
})
.then(data => renderCountry(data, 'neighbor'))
.catch(err => {
console.error(`${err} ๐ฅ๐ฅ๐ฅ`);
renderError(`Something went wrong ๐ฅ๐ฅ ${err.message}. Try again!`);
})
.finally(() => {
countriesContainer.style.opacity = 1;
});
};
btn.addEventListener('click', function () {
getCountryData('qwlikusn');
});
Throwing error manually ('No neighbor found' error)
const getCountryData = function (country) {
// country 1
getJSON(`https://restcountries.com/v2/name/${country}`, 'Country not found')
.then(data => {
renderCountry(data[0]);
const neighbor = data[0].borders?.[0]; // optional chaining for no borders
if (!neighbor) throw new Error('No neighbor found');
//country 2
return getJSON(
`https://restcountries.com/v2/alpha/${neighbor}`,
'Country not found'
);
})
.then(data => renderCountry(data, 'neighbor'))
.catch(err => {
console.error(`${err} ๐ฅ๐ฅ๐ฅ`);
renderError(`Something went wrong ๐ฅ๐ฅ ${err.message}. Try again!`);
})
.finally(() => {
countriesContainer.style.opacity = 1;
});
};
btn.addEventListener('click', function () {
getCountryData('usa');
});
// no borders
getCountryData('australia');
ย