在 vue 中使用 fetch 一次发出多个 api 请求

Making multiple api requests at once using fetch in vue

我想在我的 vue 组件中同时对 ReST API 进行两次 api 调用。我在网上做了研究,正在使用这个逻辑:

// Multiple fetches
      Promise.all([
        fetch(
          `https://api.covid19api.com/live/country/${this.selected}/status/confirmed/date/${this.yesterday}`
        ),
        fetch(
          `https://api.covid19api.com/live/country/south-africa/status/confirmed/date/2020-03-21T13:13:30Z`
        )
      ])
        .then(responses => {
          // Get a JSON object from each of the responses
          return responses.map(response => {
            return response.json();
          });
        })
        .then(data => {
          // Log the data to the console
          // You would do something with both sets of data here

          this.coronaVirusStats1 = data[0];
          console.log(this.coronaVirusStats1);
        })
        .catch(function(error) {
          // if there's an error, log it
          console.log(error);
        });
    }

安慰值是我理解的承诺,但是当我查看组件下的 Vue devTools 时,我看到 coronaVirusStats1 的值为 "Promise",而不是我期望返回的对象数组。当我执行一次获取并使用数据变量时,没有问题。但是,我对如何访问从对多个端点的提取调用返回的数据感到困惑。我在这里 尝试了所有解决方案,但 none 有效。如果有人能阐明从提取中访问数据的正确方法,我将不胜感激。

你就在那里。问题是您的第一个 then returns 一个 承诺数组 。不幸的是,承诺链只适用于 Promise 实例,所以这里没有任何东西可以等待你的承诺解决。

快速修复是将第一个 then 更改为

return Promise.all(responses.map(r => r.json()))

话虽这么说,fetch API 的功能还有很多,尤其是在处理错误方面。

我会在每个 fetch 调用中使用类似以下内容,以确保正确处理网络错误和不成功的 HTTP 请求。

这也将处理解包 JSON 响应,因此您不必使用上面的

Promise.all([
  fetch(url1).then(res => res.ok && res.json() || Promise.reject(res)),
  fetch(url2).then(res => res.ok && res.json() || Promise.reject(res))
]).then(data => {
  // handle data array here
})

https://developer.mozilla.org/en-US/docs/Web/API/Response/ok