I am fairly new with JavaScript and the flux of callbacks, so I am wondering how to achieve the next:
function getLocation() {
fetch('https://www.fakeapi.example.com/services/geo-iso.html')
.then(response => {
return response.json();
})
.then(data => {
console.log(data.iso);
})
.catch(err =>
console.error('Hubo un problema con la petición Fetch: ' + err.message)
);
}
The console.log(data.iso);
returns the country ISO reference you are visiting (like MX from Mexico, US from USA, etc).
What I want to achieve is some way to use this function and watch if it comes from US (for example) to do a different thing if it comes from another country, like:
if (getLocation() == 'MX') {
console.log('Do this');
} else if (getLocation() == 'US') {
console.log('Do that');
}
I tried putting a callback to another function that analyzes the ISO code, but it does not convince me at all.
Any idea?
Fetch returns a Promise that you can then continue the chain.
const location = getLocation(); // returns a promise
location.then((data) => {
switch (data.iso) {
case 'MX':
// Do something for Mexico
break;
case 'US':
// Do something for United States
break;
default:
// Do something with any other ISO
}
});