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

104
Vistas
Async await with Fetch

my fetch works perfectly with .then, but i want to step it up a notch by using async and await. It should wait for all 5 API calls, and then place the answer, instead, it shows answer on every API call

async function getPhotosFromAPI() {
  for (let i = 1; i <= 5; i++) {
    let albums = await fetch(
      `https://jsonplaceholder.typicode.com/photos/?albumId=${i}`
    );
    let result = await albums.json();
    let res = `<div class="album${i}"></div>`;
    document.querySelector(".display-images").innerHTML += res;
    for (let j = 1; j <= 5; j++) {
      document.querySelector(
        `.album${i}`
      ).innerHTML += `<img src="${result[j].url}"/>`;
    }
  }
  
  console.log(result);
}
async function showPhotos() {
  await getPhotosFromAPI();
  document.getElementById("#loader").style.display = "none";
}
showPhotos();

document.getElementById("img").style.display = "block";
for (let i = 1; i <= 5; i++) {
  fetch(`https://jsonplaceholder.typicode.com/photos/?albumId=${i}`)
    .then((response) => response.json())
    .then((json) => {
      document.getElementById("img").style.display = "none";

      const display = document.querySelector(".display-images");
      const albumNo = document.querySelector(".album-no");
      //   document.getElementById('img').style.display = "block";
      // document.getElementById('img').style.display = "none";]
      display.innerHTML += `<div class="album-${i}>`;
      for (let z = 1; z <= 5; z++) {
        display.innerHTML += `<img id="img" alt="pic-from-album${json[i].albumId}" src="${json[z].url}"/>`;
      }
      display.innerHTML += `<div>`;
    });
}

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

0

You're asking for the code to wait until each fetch finishes by using await on fetch's return value (then again on the return value of json) in your loop. So it will do just that: wait until that request is complete before moving on to the next loop iteration.

If you don't want to do that, you need to start each fetch one after another and then wait for them all to complete. I'd probably break out the work for just one of them into a function, then call it five times, building an array of the promises it returns, then await Promise.all(/*...*/) those promises, something along these lines:

document.getElementById("img").style.display = "block";
// Fetch one item
const fetchOne = async (i) => {
    const response = await fetch(`https://jsonplaceholder.typicode.com/photos/?albumId=${i}`);
    if (!response.ok) {
        throw new Error(`HTTP error ${response.status}`);
    }
    const data = await response.json();
    document.getElementById("img").style.display = "none";

    const display = document.querySelector(".display-images");
    const albumNo = document.querySelector(".album-no");
    //   document.getElementById('img').style.display = "block";
    // document.getElementById('img').style.display = "none";]
    display.innerHTML += `<div class="album-${i}>`;
    for (let z = 1; z <= 5; z++) {
        display.innerHTML += `<img id="img" alt="pic-from-album${data[i].albumId}" src="${data[z].url}"/>`;
    }
    display.innerHTML += `<div>`;
};
// ...
await Promise.all(Array.from({length: 5}, (_, i) => fetchOne(i + 1)));
// All done

(I took the version with .then as my starting point for the above, since the two versions in your question were so different and you said the one with .then worked... Also note that I renamed the variable json to data, since it doesn't contain JSON [it's not a string], it contains the result of parsing JSON.)

about 4 years ago · Juan Pablo Isaza Denunciar

0

You should use a concurrent way of fetching like Promise.all to avoid round-trips

async function getPhotosFromAPI() {
  let albums = await Promise.all(
    Array(5).fill().map((elem, index) => 
      fetch(`https://jsonplaceholder.typicode.com/photos/?albumId=${index+1}`)
    )
  )
  let results = await Promise.all(
    albums.map(album => album.json())
  )
  return results
}
//Display
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