异步等待提取

发布于 2025-02-11 02:02:24 字数 1771 浏览 2 评论 0原文

我的获取与。然后,我想通过使用async等待来提高档位。它应该等待所有5个API呼叫,然后放置答案,而是在每个API呼叫上显示答案

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>`;
    });
}

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>`;
    });
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

岁月静好 2025-02-18 02:02:24

您应该使用一种同时提取的方式,例如承诺。

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())
  )
  console.log(results)
  return results
}

getPhotosFromAPI()

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())
  )
  console.log(results)
  return results
}

getPhotosFromAPI()

三人与歌 2025-02-18 02:02:24

您是您要求代码等到每个fetch通过使用等待 on fetch的返回值(然后再次在返回值上, JSON)在您的循环中。因此,它将做到这一点:等到该请求完成,然后再进行下一个循环迭代。

如果您不想这样做,则需要一个接一个地启动每个Fetch,然后等待所有人完成。我可能只将其中一个用于一个功能,然后将其称为五次,建立返回的承诺的数组,然后等待Promise.all(/*....*/)< /code>那些承诺,沿着这些行:(

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

我以。 ],它包含解析 JSON的结果。

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.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文