【问题标题】:How to fetch multiple GET URLs at once [closed]如何一次获取多个 GET URL [关闭]
【发布时间】:2022-01-06 21:56:13
【问题描述】:
fetch(`./User.json`, { method: "get" })
.then(response => response.json())
.then(data =>
    data.results.forEach(result => (list.innerHTML += template(result)))
)
.catch(error => console.log(error));

我想添加一些 json 数据。有什么解决办法。 这是我的代码。

【问题讨论】:

标签: javascript json api get fetch-api


【解决方案1】:

您可以使用 Promise.all method 来获取 fetch 调用的值,一旦所有的 Promise 都解决了,您将获得一个数组中的值,您可以如下所示进行销毁

    Promise.all([fetch(`./User.json`, { method: "get" }).then(response => response.json())]), fetch(`./Products.json`, { method: "get" }).then(response => response.json())]).then([users, products]=>
    users.results.forEach(result => (list.innerHTML += template(result)))
)

【讨论】:

    【解决方案2】:

    假设您希望所有请求都完成,而不管它们的响应状态如何,那么Promise.allSettled() 是一个很好的选择

    // handy "get" shortcut with error handling
    const get = async (url) => {
      const res = await fetch(url) // "GET" is the default method
      if (!res.ok) {
        throw new Error(`${res.status}: ${await res.text()}`)
      }
      return res.json()
    }
    
    const urls = ["./Foo.json", "./Bar.json", "./Baz.json"]
    
    Promise.allSettled(urls.map(get)).then(responses => {
      const data = responses
        .filter(({ status }) => status === "fulfilled")
        .map(({ value }) => value)
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-20
      • 2021-12-08
      相关资源
      最近更新 更多