Exploring the concepts of promises, await, and async functions has been a fascinating journey for me. As I delved into promises, I discovered an interesting aspect - the unpredictable order in which requests were resolved when multiple requests were sent out simultaneously. Due to network routing and packet handling, the requests did not necessarily return in the same sequence as they were written in the code.
const getCountry = async country => {
await fetch(`https://restcountries.com/v2/name/${country}`)
.then(res => res.json())
.then(data => {
console.log(data[0]);
})
.catch(err => err.message);
};
getCountry('portugal');
getCountry('ecuador');
Before diving into the world of async and await, I found a solution that suited my needs perfectly. By incorporating these features, each request now waits for the previous one to complete before proceeding.
I wonder if there is a simpler way to achieve this? Are there any unnecessary redundancies that can be eliminated from the code? I am open to suggestions but prefer to stick with what works well for me.
await fetch(`https://restcountries.com/v2/name/${country}`)
.then(res => res.json())
.then(data => {
console.log(data[0]);
})
.catch(err => err.message);
};
const getCountryData = async function () {
await getCountry('portugal');
await getCountry('ecuador');
};
getCountryData();
Appreciate your input,