Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

207
Vistas
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,

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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
);
about 4 years ago · Juan Pablo Isaza Denunciar

0

I tried it the way @deceze recommended and it works fine: I removed all of the .then and replaced them with await. A lot cleaner this way. Now I can use normal try and catch blocks.

// GET COUNTRIES IN ORDER
const getCountry = async country => {
  try {
    const status = await fetch(`https://restcountries.com/v2/name/${country}`);
    const data = await status.json();
    renderCountry(data[0]); // Data is here. Now Render HTML
} catch (err) {
    console.log(err.name, err.message);
  }
};

const getCountryData = async function () {
  await getCountry('portugal');
  await getCountry('Ecuador');
};

btn.addEventListener('click', function () {
  getCountryData();
});

Thank you all.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda