Learning Promises, Async/Await to control execution order

I have been studying promises, await and async functions. While I was just in the stage of learning promises, I realized that the following: When I would send out two requests, there was no guarantee that they would come in the order that they are written in the code. Of course, with routing and packets of a network. When I ran the code below, the requests would resolve in no specific order.

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');

At this point, I hadn't learned about async and await. So, the following code works the exact way I want it. Each request, waits until the other one is done.

Is this the most simple way to do it? Are there any redundancies that I could remove? I don't need a ton of alternate examples; unless I am doing something wrong.

  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();

Thanks in advance,


Solution 1:

Yes, that's the correct way to do so. Do realize though that you're blocking each request so they run one at a time, causing inefficiency. As I mentioned, the beauty of JavaScript is its asynchronism, so take advantage of it. You can run all the requests almost concurrently, causing your requests to speed up drastically. Take this example:

// get results...
const getCountry = async country => {
  const res = await fetch(`https://restcountries.com/v2/name/${country}`);
  const json = res.json();
  return json;
};

const getCountryData = async countries => {
  const proms = countries.map(getCountry); // create an array of promises
  const res = await Promise.all(proms); // wait for all promises to complete

  // get the first value from the returned array
  return res.map(r => r[0]);
};

// demo:
getCountryData(['portugal', 'ecuador']).then(console.log);
// it orders by the countries you ordered
getCountryData(['ecuador', 'portugal']).then(console.log);
// get lots of countries with speed
getCountryData(['mexico', 'china', 'france', 'germany', 'ecaudor']).then(console.log);

Edit: I just realized that Promise.all auto-orders the promises for you, so no need to add an extra sort function. Here's the sort fn anyways for reference if you take a different appoach:

myArr.sort((a, b) => 
  (countries.indexOf(a.name.toLowerCase()) > countries.indexOf(b.name.toLowerCase())) ? 1 :
  (countries.indexOf(a.name.toLowerCase()) < countries.indexOf(b.name.toLowerCase()))) ? -1 :
  0
);