【问题标题】:Chained Fetch getting first results immediately链式获取立即获得第一个结果
【发布时间】:2021-04-26 07:54:28
【问题描述】:

我正在发送链接的Fetch 请求。首先,我从数据库中检索数据并请求与我获得的每个标题相关的图片。

在发送图像requests 之前,HTML 代码不会加载到结果div。所以看文章需要很长时间。如何在图像requests 开始发送之前加载文本?

async function getArticles(params) {
    url = 'http://127.0.0.1:8000/articles/api/?'
    url2 = 'https://api.unsplash.com/search/photos?client_id=XXX&content_filter=high&orientation=landscape&per_page=1&query='

    const article = await fetch(url + params).then(response => response.json());

    const cards = await Promise.all(article.results.map(async result => {
        try {
            let image = await fetch(url2 + result.title).then(response => response.json())

            let card = // Creating HTML code by using database info and Splash images
            return card

        } catch {
            let card = // Creating HTML code by using info and fallback images from database
            return card
        }
    }))
document.getElementById('results').innerHTML = cards.join("")

};

我曾尝试单独使用它们,但我得到了 Promise 对象。

【问题讨论】:

  • 不要使用Promise.all(),它会等待它们全部解决。使用 for 循环执行 await fetch 并按顺序将该响应添加到 DOM。
  • @Barmar 谢谢,你能添加代码吗?我不知道在哪里使用该循环以及如何使用。因为我已经在映射第一次获取的结果

标签: javascript async-await fetch-api


【解决方案1】:

如果您不想等待所有提取,请使用普通的for 循环并依次等待每个提取。

async function getArticles(params) {
  url = 'http://127.0.0.1:8000/articles/api/?'
  url2 = 'https://api.unsplash.com/search/photos?client_id=XXX&content_filter=high&orientation=landscape&per_page=1&query='

  const article = await fetch(url + params).then(response => response.json());

  for (let i = 0; i < article.results.length; i++) {
    let result = article.results[i];
    let card;
    try {
      let image = await fetch(url2 + result.title).then(response => response.json())
      card = // Creating HTML code by using database info and Splash images
    } catch {
      card = // Creating HTML code by using info and fallback images from database
    }
    document.getElementById('results').innerHTML += card;
  }
}

但是,这会更慢,因为它不会在前一个完成之前开始每次提取。

很难同时运行所有提取,而是按发送顺序而不是接收响应的顺序显示结果。您可以在发送前为每个响应创建一个容器 DIV,然后在收到响应时填写相应的 DIV。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-15
    • 1970-01-01
    • 2016-09-05
    • 2018-06-25
    相关资源
    最近更新 更多